如何使用 jQuery 從表中刪除行?
使用事件委託在網頁上用 jQuery 新增按鈕,既能新增新行又能刪除表格行。
首先,設定“刪除”按鈕
<button type="button" class="deletebtn" title="Remove row">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>
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP