如何使用jQuery从表中删除表行
jQuery remove()方法是用来从HTML表格中删除一行的。
jQuery remove() Method :该方法删除所选元素以及文本和子节点。这个方法也删除了所选元素的数据和事件。
语法:
$(selector).remove(selector)
参数:它接受单参数选择器,这是可选的。它指定了一个或多个要删除的元素。如果要删除多个元素,请用逗号(,)操作符将它们分开。
例子1:这个例子首先通过id值选择行,然后通过remove()方法将其删除。
<!DOCTYPE HTML>
<html>
<head>
<title>
How to remove a table row
from table
</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
<style>
#myCol {
background:green;
}
table {
color:white;
}
#Geek_p {
color:green;
font-size:30px;
}
td {
padding:10px;
}
</style>
</head>
<body>
<center>
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<table>
<colgroup>
<col id="myCol"
span="2">
<col style="background-color:green">
</colgroup>
<tr>
<th>S.No</th>
<th>Title</th>
<th>Geek_id</th>
</tr>
<tr id = "row1">
<td>Geek_1</td>
<td>GeekForGeeks</td>
<th>Geek_id_1</th>
</tr>
<tr>
<td>Geek_2</td>
<td>GeeksForGeeks</td>
<th>Geek_id_2</th>
</tr>
</table>
<br>
<button onclick = "Geeks()">
Click here
<!-- Script to remove table row from table -->
<script>
function Geeks() {
$("#row1").remove();
}
</script>
</center>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
例子2:这个例子首先选择其父辈的最后一个<tr>
元素,并通过remove()方法将其删除。
<!DOCTYPE HTML>
<html>
<head>
<title>
How to remove table row
from table
</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
<style>
#myCol {
background:green;
}
table {
color:white;
}
#Geek_p {
color:green;
font-size:30px;
}
td {
padding:10px;
}
</style>
</head>
<body>
<center>
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<table>
<colgroup>
<col id="myCol"
span="2">
<col style="background-color:green">
</colgroup>
<tr>
<th>S.No</th>
<th>Title</th>
<th>Geek_id</th>
</tr>
<tr id = "row1">
<td>Geek_1</td>
<td>GeekForGeeks</td>
<th>Geek_id_1</th>
</tr>
<tr>
<td>Geek_2</td>
<td>GeeksForGeeks</td>
<th>Geek_id_2</th>
</tr>
</table>
<br>
<button onclick = "Geeks()">
Click here
<script>
function Geeks() {
$('tr:last-child').remove();
}
</script>
</center>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
jQuery是一个开源的JavaScript库,它简化了HTML/CSS文档之间的交互,它以其 “少写多做 “的理念而广为人知。
你可以通过学习这个jQuery教程和jQuery实例,从基础开始学习jQuery。