JavaScript 如何隐藏除了选中项以外的所有行而不知道完整的ID
给定一个具有固定行数的HTML表格,任务是使用JavaScript隐藏除了选中项以外的所有行,而不知道其ID。
方法: 使用querySelectorAll(),forEach(),addEventListener()和filter()等方法以及原生JavaScript中的spread运算符(…)。
首先,我们使用querySelectorAll()方法选择除标题行外的所有表格行,将tr:not(:first-child)选择器作为字符串参数传递给它。然后,我们使用forEach()方法遍历每一行。现在,对于每一行,使用addEventListener()方法附加一个事件监听器,事件为点击事件。 在事件监听器中,声明一个变量row,它以数组的形式存储所有的表格行元素,因为使用spread操作符将querySelectorAll()方法返回的节点列表转换为数组。我们使用filter()方法从所有的行中过滤出特定的行,其中传递一个参数element。过滤行的条件是,如果行没有被点击,我们应该使用display属性将其隐藏,display属性的值被设置为none。
示例: 在这个例子中,我们使用了上述解释的方法。
HTML
<!DOCTYPE html>
<html>
<head>
<style>
body {
text-align: center;
}
h1 {
color: green;
font-size: 2.5rem;
}
p {
font-size: 1.5rem;
font-weight: bold;
}
table {
margin: 0 auto;
}
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
th,
td {
padding: 0.5rem;
}
tr:not(:first-child) {
cursor: pointer;
}
tr:not(:first-child):hover {
background: green;
color: white;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<p>JavaScript - Hide all rows except
selected one without ID
</p>
<table>
<tr>
<th>Book Name</th>
<th>Author Name</th>
<th>Genre</th>
</tr>
<tr>
<td>The Book Thief</td>
<td>Markus Zusak</td>
<td>Historical Fiction</td>
</tr>
<tr>
<td>The Cruel Prince</td>
<td>Holly Black</td>
<td>Fantasy</td>
</tr>
<tr>
<td>The Silent Patient</td>
<td>Alex Michaelides</td>
<td>Psychological Fiction</td>
</tr>
</table>
<script>
document.querySelectorAll(
// Select all rows except the first one
"tr:not(:first-child)").forEach(function (e) {
// Add onClick event listener
// to selected rows
e.addEventListener("click", function () {
// Get all rows except the first one
var rows =
[...document.querySelectorAll(
"tr:not(:first-child)"
)];
var notSelectedRows =
rows.filter(function (element) {
// Hide the rows that have
// not been clicked
if (element !== e) {
element.style.display = "none";
}
});
});
});
</script>
</body>
</html>
输出: