我有一个表单,用户可以在其中动态添加行并删除它们。我的问题是删除功能仅在单击FIRST行上的删除按钮时有效,并且它删除了最后一行,显然是因为我写了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"/>
答案 0 :(得分:4)
您需要使用事件委派将事件附加到动态添加的元素。使用:
$("body").on('click','.deleteThisRow',function(){
if($('.orderForm tr').length>1){
$(this).closest('tr').remove();
}else{
alert('One row should be present in table');
}
});