问题
<button id="btn">Car</button>
<button id="btn1">Bike</button>
<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>
<script>
$(function () {
$("#btn").click(function() {
var type = $(this).text();
$('td:first-child').parent('tr:not(:contains('+type+'))').toggle();
});
$("#btn1").click(function() {
var type = $(this).text();
$('td:first-child').parent('tr:not(:contains('+type+'))').toggle();
});
});
</script>
Adding to: Filtering: How to hide/show (toggle) certain table rows on click? Based on the solution provided by Itotally, I am filtering table rows based on the button(s) text. Is this the most efficient solution?
回答1:
There is some other solutions
You can add a select with your choice and show only the selected item
Add the class type on td where you search.
Demo
$("#choice").change(function(){
var choice = $(this).val().toUpperCase();
$("table tr").each(function (index) {
if (index !== 0) {
$row = $(this);
var id = $row.find("td.type").text().toUpperCase();
if (id.indexOf(choice) == -1) {
$row.hide();
}
else {
$row.show();
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="choice">
<option value>All</option>
<option value="Bike">Bike</option>
<option value="Car">Car</option>
</select>
<table id="vehicles">
<tr>
<th>Type</th>
<th>Color</th>
<th>Wheels</th>
</tr>
<tr>
<td class="type">Car</td>
<td>Red</td>
<td>4</td>
</tr>
<tr>
<td class="type">Motorcycle</td>
<td>Green</td>
<td>2</td>
</tr>
<tr>
<td class="type">Bike</td>
<td>Blue</td>
<td>2</td>
</tr>
<tr>
<td class="type">Car</td>
<td>Blue</td>
<td>4</td>
</tr>
<tr>
<td class="type">Bike</td>
<td>Green</td>
<td>2</td>
</tr>
<tr>
<td class="type">Motorcycle</td>
<td>Red</td>
<td>2</td>
</tr>
</table>
This can minimize your number of button if there is a lot of choice
You can easily add a search in your table too
HTML
<input type="text" name="search" id="search">
Jquery
$("#search").keyup(function(){
var search = $(this).val();
$('td:first-child').parent('tr:not(:contains('+search+'))').toggle();
});
来源:https://stackoverflow.com/questions/35632168/i-want-to-toggle-the-table-rows-filter-based-on-the-text-from-buttons