2013-01-23 32 views
1

聲明:HTML,JQuery,Ajax技能級別 - 垃圾。始終是一個厚厚的客戶。使用jquery將<span> html更改爲<tr> ...</tr>

我有一個表格,允許用戶輸入客戶代碼和電子郵件地址。我想在客戶代碼有效時顯示客戶的姓名。我會通過Ajax和Spring MVC的方式大失所望,但作爲第一步,我想我會使用jquery函數在客戶代碼下的表中添加一行。然而,我無法讓它工作。

這裏是我的JSP:

<%@include file="/common/header.jsp" %> 
<h1> 
    <a href="/customerEmailList.do"><spring:message code="customer.email.title"/></a> 
    <span class="breadcrumb"><spring:message code="ui.breadcrumb.separator"/></span> 
    <spring:message code="action.add"/> 
</h1> 
<form:form action="customerEmailAdd.do" commandName="customerEmailEntry"> 
    <table> 
     <tr> 
      <td colspan="3"><form:errors cssClass="error"/></td> 
     </tr> 
     <tr> 
      <td><spring:message code="customer.email.code"/> <span class="mandatory">*</span></td> 
      <td><form:input id="customerCode" path="customerCode" maxlength="8" size="10"/></td> 
      <td><form:errors path="customerCode" cssClass="error"/></td> 
     </tr> 
     <span id="identifiedCustomer"> 
     </span> 
     <tr> 
      <td><spring:message code="customer.email.edit.field"/> <span class="mandatory">*</span></td> 
      <td><form:input path="emailAddress" maxlength="255" size="50"/></td> 
      <td><form:errors path="emailAddress" cssClass="error"/></td> 
     </tr> 
     <tr> 
      <td colspan="3"> 
       <hr/> 
      </td> 
     </tr> 
     <tr> 
      <td colspan="3" align="right"> 
       <input type="submit" class="green-button" value="<spring:message code="button.save"/>"/> 
      </td> 
     </tr> 
    </table> 
</form:form> 

<script type="text/javascript"> 
    $ (document).ready (function() { 
     $ ('#identifiedCustomer').html ('<tr><td>Hello, world</td></tr>'); 
    });  
</script> 

<%@include file="/common/footer.jsp" %> 

的jQuery(1.8.3)正在通過共同的頭拉入。

當窗體加載時,顯示文本世界,但它不是新的表格行。它在表格前出現。我預料它會在customerCodeemailAddress字段行之間創建一個新行。

我做錯了什麼?

回答

3

而不是使用.html使用.replaceWith

.html的變化跨度的內容,但不會刪除它們。桌子中間的跨度和自己的<tr>無效。 .replaceWith將創建一個新元素並從DOM中刪除<span>

但是,根據DOM的結構,這可能會導致問題,因爲跨度始於無效點。爲什麼不使用<tr id="identifiedCustomer">而不是<span>

+0

謝謝。這工作。 – Andrew

2

你不能只在table的中間有span。這是無效的HTML。你必須使用一個tr代替:

<tr> 
    <td><spring:message code="customer.email.code"/> <span class="mandatory">*</span></td> 
    <td><form:input id="customerCode" path="customerCode" maxlength="8" size="10"/></td> 
    <td><form:errors path="customerCode" cssClass="error"/></td> 
</tr> 
<tr id="identifiedCustomer"></tr> 
<tr> 
    <td><spring:message code="customer.email.edit.field"/> <span class="mandatory">*</span></td> 
    <td><form:input path="emailAddress" maxlength="255" size="50"/></td> 
    <td><form:errors path="emailAddress" cssClass="error"/></td> 
</tr> 

的jQuery:

$(document).ready (function() { 
    $('#identifiedCustomer').html('<td>Hello, world</td>'); 
}); 
+0

賓果。完善。謝謝你,約瑟夫。 – Andrew

0

你想要做的是

$('table tbody').append('<tr><td>Hello, world</td></tr>'); 

,將選擇表的TBODY和將新行添加到最後。

理想情況下,您需要在表格中添加一個ID,這樣您最終不會向頁面上的每個表格添加新行。

+0

我不希望最後一行出現 - 我希望它出現在客戶代碼下。 – Andrew

相關問題