0

我使用jQuery添加和删除表格行。我可以轻松添加行,但无法删除已创建的行。动态添加和删除表格行

您可以在此处查看页面的操作:http://freshbaby.com/v20/wic/request_quote.cfm,粘贴下面的相关代码。

HTML

<table style="width:600px;" id="product-list" summary="Lists details about products users wish to purchase"> 
    <thead valign="top" align="left"> 
     <tr> 
      <th>Products</th> 
      <th>Language</th> 
      <th>Quantity</th> 
      <th></th> 
     </tr> 
    </thead> 
    <tbody valign="top" align="left"> 
     <tr> 
      <td> 
       <cfselect query="getProductListing" name="product" size="1" display="name" value="name" queryPosition="below"> 
        <option value=""></option> 
       </cfselect> 
      </td> 
      <td> 
       <select name="language" size="1"> 
        <option value="English">English</option> 
        <option value="Spanish">Spanish</option> 
       </select> 
      </td> 
      <td> 
       <cfinput name="quantity" required="yes" message="Enter your desired quantity" size="10" maxlength="3" mask="999"> 
      </td> 
      <td valign="bottom"><a href="javascript://" class="addrow">Add Another Product</a></td> 
     </tr> 
    </tbody> 
</table> 

的JavaScript:

<script> 
     $(function() { 
      var i = 1; 
      $(".addrow").click(function() { 
       $("table#product-list tbody > tr:first").clone().find("input").each(function() { 
        $(this).attr({ 
         'id': function(_, id) { return id + i }, 
         'value': ''    
        }); 
       }).end().find("a.addrow").removeClass('addrow').addClass('removerow').text('< Remove This Product') 
       .end().appendTo("table#product-list tbody"); 
       i++; 
       return false; 
      }); 

      $("a.removerow").click(function() { 
        //This should traverse up to the parent TR 
       $(this).parent().parent().remove(); 
       return false; 
      }); 
     }); 
    </script> 

当我点击链接,删除上述链路包含在该行,什么都不会发生。没有脚本错误,所以它必须是逻辑。

+1

尝试使用'$(this).closest('tr')。remove();'而不是。如果这不起作用,请尝试使用'e.preventDefault();'而不是'return false;',但将其放在函数的顶部。 – slamborne 2013-02-27 03:29:03

+0

我认为它会工作 – PSR 2013-02-27 03:29:39

+0

它不;看看为什么在下面的答案。 – 2013-02-27 12:57:05

回答

1

试试这个

$("#product-list").on('click','a.removerow',function(e) { 
    e.preventDefault(); 
    //This should traverse up to the parent TR 
    $(this).closest('tr').remove(); 
    return false; 
}); 

这将确保新创建的元素可以被删除。当您使用$("a.removerow").click(..时,它只会影响存在的元素(无),而不会影响将动态创建的元素。

+0

好的答案,我学到了一些关于不存在的元素互动的新东西。精彩! – 2013-02-27 12:56:44