如何使用 jQuery 从表中删除一行?
jqueryjavascript更新于 2024/3/10 15:40:17
使用事件委托在网页上使用 jQuery 添加新行和删除表行的按钮。
首先,设置删除按钮:
<button type="button" class="deletebtn" title="删除行>>X</button>
要在单击按钮时触发事件,请使用 jQuery on() 方法:
$(document).on('click', 'button.deletebtn', function () {
$(this).closest('tr').remove();
return false;
});
以下是使用 jQuery 从表中删除一行的完整代码:
示例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var x = 1;
$("#newbtn").click(function () {
$("table tr:first").clone().find("input").each(function () {
$(this).val('').attr({
'id': function (_, id) {
return id + x
},
'name': function (_, name) {
return name + x
},
'value': ''
});
}).end().appendTo("table");
x++;
});
$(document).on('click', 'button.deletebtn', function () {
$(this).closest('tr').remove();
return false;
});
});
</script>
</head>
<body>
<table>
<tr>
<td>
<button type="button" class="deletebtn" title="Remove row">X</button>
</td>
<td>
<input type="text" id="txtTitle" name="txtTitle">
</td>
<td>
<input type="text" id="txtLink" name="txtLink">
</td>
</tr>
</table>
<button id="newbtn">Add new Row</button>
</body>
</html>
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

