[英]Hide/show (toggle) table rows on click
$(function () {
$( "td" ).on( "click", function() {
var type = $(this).text();
$('td:first-child').parent('tr:not(:contains('+type+'))').toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="vehicles">
<tr>
<th>Type</th>
<th>Color</th>
<th>Wheels</th>
</tr>
<tr>
<td>Car</td>
<td>Red</td>
<td>4</td>
</tr>
<tr>
<td>Motorcycle</td>
<td>Green</td>
<td>2</td>
</tr>
<tr>
<td>Bike</td>
<td>Blue</td>
<td>2</td>
</tr>
<tr>
<td>Car</td>
<td>Blue</td>
<td>4</td>
</tr>
<tr>
<td>Bike</td>
<td>Green</td>
<td>2</td>
</tr>
<tr>
<td>Motorcycle</td>
<td>Red</td>
<td>2</td>
</tr>
</table>
跟进: 如何在单击时隐藏/显示(切换)某些表行? 只要打开/关闭表元素,此方法就起作用,但是如果您在一行中选择一个项目,然后在另一行中选择一个项目,则过滤变得混乱。
也许有更好的方法来执行此操作,但是如果您仅跟踪最后单击的类型以及表是否已被过滤,则可以更清楚地了解何时需要重置表或应用过滤器。
https://jsfiddle.net/wilchow/stnnuw0a/1/
$(function () {
var last_type = null;
var filtered = false;
$( "td" ).on( "click", function() {
console.log("last_type: "+last_type);
var type = $(this).text();
console.log("type: "+type);
if(filtered && last_type == type) {
// type is already filtered. Show all.
$("tr, td").show();
last_type = null; // reset
filtered = false; // reset
} else {
$("tr, td").show(); // show all before filtering
$('td:first-child').parent('tr:not(:contains('+type+'))').hide();
filtered = true; // set filter flag to true
}
last_type = type; // set last type clicked
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.