gpt4 book ai didi

jquery - 删除动态添加的表行

转载 作者:行者123 更新时间:2023-12-01 03:12:15 26 4
gpt4 key购买 nike

我有一个表单,用户可以在其中动态添加行和删除行。我的问题是,删除功能仅在单击第一行上的删除按钮时才起作用,并且它删除了最后一行,显然是因为我已经编写了 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"/>

最佳答案

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

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

关于jquery - 删除动态添加的表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25668275/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com