如何使用jQuery在表格中添加新行?
使用事件委托可以包括使用jQuery在网页上添加新行和删除表行。
首先,在HTML中设置一个按钮以添加新行
<button id="newbtn"> Add new Row </button>
现在,在按钮单击事件下,设置代码:
$("#newbtn").click(function () {
}示例
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.staticfile.org/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>热门推荐
10 高一祝福语简短 励志
11 立秋节气简短祝福语
12 简短公司周年祝福语大全
13 中考感言简短祝福语大全
14 体育老师简短祝福语
15 干杯生日祝福语简短独特
16 特别简短的祝福语老师
17 朋友坐车走了祝福语简短
18 给英雄的祝福语简短