2014-09-04 125 views
2

我有一个表单,用户可以在其中动态添加行并删除它们。我的问题是,删除功能只有在单击第一行上的删除按钮时才起作用,并且删除了最后一行,显然是因为我写了tr:last。我尝试了所有可以在互联网上找到/找到的组合,并且我似乎无法弄清楚如何删除最后一行以外的行。理想情况下,我想每行都有一个删除按钮,删除按钮会从表中删除该特定行,而不是最后一行。任何帮助,将不胜感激。谢谢!删除动态添加的表格

<script> 
$(document).ready(function(){ 
//This line clones the row inside the '.row' class and transforms it to plain html. 
var clonedRow = $('.row').clone().html(); 

//This line wraps the clonedRow and wraps it <tr> tags since cloning ignores those tags 
var appendRow = '<tr class = "row">' + clonedRow + '</tr>'; 

$('#btnAddMore').click(function(){ 
//this line get's the last row and appends the appendRow when it finds the correct row. 
    $('.orderForm tr:last').after(appendRow); 
}); 



$(".deleteThisRow").click(function(){ 
     if($('.orderForm tr').size()>1){ 
      $('.orderForm tr:last').remove(); 
     }else{ 
      alert('One row should be present in table'); 
     } 
    }); 
}); 

</script> 

<table class="orderForm" id="orderForm" width="100%"> 
     <tr class="row">  
     <td> 
     <div class="pure-control-group"> 
      <label>Product or Service</label><select name="product[]" id="product"> 
      <option value=""></option> 
      <?php while($productRow = mysql_fetch_assoc($productResult)){?> 
        <option value="<?php echo $productRow['prouct_id'];?>" data-price="$<?php echo $productRow['price']; ?>"><?php echo $productRow['product']; ?></option> 
          <?php } ?> 
         </select> 

    </div> 
    <div class="pure-control-group"> 

     <label>Price</label><input type="text" id="price" name="price[]"> 
     </div> 
     <input type="button" class="deleteThisRow" id="deleteThisRow" value="Delete"/> 
     </td> 
     </tr> 
     </table> 
     <input type="button" id="btnAddMore" value="Add Product or Service" class="pure-button"/> 

回答

4

您需要使用事件委托来将事件附加到动态添加的元素。使用:

$("body").on('click','.deleteThisRow',function(){ 
    if($('.orderForm tr').length>1){ 
     $(this).closest('tr').remove(); 
    }else{ 
     alert('One row should be present in table'); 
    } 
}); 
+1

'.size()'=>'.length'会更好 – 2014-09-04 14:38:45

+0

@AmitJoki:确实.. !! – 2014-09-04 14:39:29

+0

@MilindAnantwar谢谢!这使得所有的按钮都可以工作,但它仍然只删除最后一行,而不是每个删除按钮所在的行。有关于此的任何想法? – 2014-09-04 14:42:16