1 回答

TA貢獻1880條經(jīng)驗 獲得超4個贊
你可以這樣做:
$(document).ready(function() {
// Map regions to cities
const regions = {
'central': ['Chicago', 'Madison', 'Dallas'],
'east': ['New York', 'Boston'],
'west': ['Seattle', 'Los Angeles'],
}
$("input[type='checkbox']").change(function() {
var locations = [];
var hideNoAges = $('#hideAge').is(":checked")
// Get ids of each region checkbox checked
$(".location:input[type='checkbox']").each(function() {
if ($(this).is(":checked")) {
locations.push($(this).attr('id'));
}
})
// Get list of all cities to be included in filter
var cities = locations.map(function(i) {
return regions[i].join();
}).join().split(",");
if (cities == "" && !hideNoAges) { // if no filters selected, show all items
$("#indexTable tbody tr").show();
} else { // otherwise, hide everything...
$("#indexTable tbody tr").hide();
$("#indexTable tbody tr").each(function() {
var show = false;
var row = $(this);
if (hideNoAges) {
if (row.find('td').eq(2).text() == "Unknown") {
show = false;
} else {
show = true;
if (cities != "") {
cities.forEach(function(city) {
if (row.find('td').eq(1).text() != city) {
show = false;
}
});
}
}
}
cities.forEach(function(city) {
if (row.find('td').eq(1).text() == city) {
show = true;
if (hideNoAges && row.find('td').eq(2).text() == "Unknown") {
show = false;
}
}
})
if (show) {
row.show();
}
})
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="indexTable">
<thead>
<tr>
<th>Name</th>
<th>Location</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bob</td>
<td>Chicago</td>
<td>24</td>
</tr>
<tr>
<td>Mike</td>
<td>New York</td>
<td>Unknown</td>
</tr>
<tr>
<td>Sarah</td>
<td>Seattle</td>
<td>30</td>
</tr>
<tr>
<td>Bill</td>
<td>Los Angeles</td>
<td>51</td>
</tr>
<tr>
<td>Gary</td>
<td>Boston</td>
<td>37</td>
</tr>
<tr>
<td>Melissa</td>
<td>Madison</td>
<td>Unknown</td>
</tr>
<tr>
<td>Greg</td>
<td>Dallas</td>
<td>61</td>
</tr>
</tbody>
</table>
<h5>Age Filter</h5>
<label for="hideAge">Hide unknown ages</label>
<input type="checkbox" id="hideAge">
<h5>Region Filter</h5>
<div>
<label for="east">East</label>
<input type="checkbox" id="east" class="location">
</div>
<div>
<label for="central">Central</label>
<input type="checkbox" id="central" class="location">
</div>
<div>
<label for="west">West</label>
<input type="checkbox" id="west" class="location">
</div>
添加回答
舉報