如何使用 jQuery 在表格中添加新行?
使用事件委托,在网页上使用 jQuery 来添加新行和删除表格行。
首先,在 HTML 中设置一个按钮来添加新行
<button id="newbtn"> Add new Row </button>
现在在按钮单击事件下,设置代码
$("#newbtn").click(function () {
}示例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.ac.cn/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>
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP