我正在尝试使用带有复选框的Jquery将多个过滤器应用于表格。我想对“位置和年龄”列进行筛选。位置筛选器工作正常。例如,选中“东”复选框将仅显示城市映射到“东”的行。
我还需要过滤年龄列,并有一个复选框,如果选中,应该隐藏“未知”年龄。除了位置过滤器之外,还应应用此过滤器。例如,选中“隐藏未知年龄”和“东方”应仅显示东部地区有年龄的人。我将复选框的状态存储为布尔值,但我在代码中实现此内容时遇到问题。我正在考虑检查布尔值并在之前对代码进行分支(如果(cities == “”),但我认为这会导致大量重复的代码。JS小提琴:https://jsfiddle.net/qjfxgkon/
$(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(",");
// Branch code here? if (!hideNoAges)..... else.......
if (cities == "") {// 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);
//show only rows that match city name
cities.forEach(function (city) {
if (row.find('td').eq(1).text() == city) { show = true; }
})
if (show) { row.show(); }
})
}
})
})
宝慕林4294392
慕村225694
随时随地看视频慕课网APP
相关分类