这是我的HTML代码,包含所有的过滤器:
<div class="search-filters">
<div class="filter-block">
<label for="employee_type">Employee Type</label>
<select id="employee_type" class="category">
<option value="0">All</option>
<option value="designer">Designer</option>
<option value="manager">Manager</option>
<option value="developer">Developer</option>
<option value="quality-assurance">Quality Assurance</option>
</select>
</div>
<div class="filter-block">
<label for="years_xp">Years Experience</label>
<select id="years_xp" class="category">
<option value="0">Select years Experience</option>
<option value="1">1 year</option>
<option value="2">2 years</option>
<option value="3">3 years</option>
</select>
</div>
</div>
我的结果列表如下:
<ul class="result-set">
<li class="result" data-employee-type="designer" data-xp="3" >John Smith</li>
<li class="result" data-employee-type="manager" data-xp="2" >Billy Joe</li>
<li class="result" data-employee-type="developer" data-xp="5" >John Appleseed</li>
</ul>
我想使用jQuery和数据属性以及选择下拉框的改变来过滤结果。目前,我的jQuery代码只能支持其中一个过滤器的工作。我尝试在jQuery中使用.filter函数,但它仍然只适用于一个下拉框的更改。如果我更改两个下拉框,它似乎会忽略一个条件。
我的jQuery代码如下:
var category_filters = [];
$('.category').on('change', function() {
category_filters = [];
$('.search-filters select').each(function() {
if ($(this).val() != 0) {
var category = $(this).val();
category_filters[$(this).attr('id')] = category;
}
});
var employee_type = "";
var years_xp = "";
if ('employee_type' in category_filters) {
employee_type = category_filters['employee_type'];
}
if ('years_xp' in category_filters) {
years_xp = category_filters['years_xp'];
}
$(".result-set .result").hide().filter(function() {
if (employee_type != "") {
if ($(this).attr('data-employee-type') == employee_type) {
return true;
}
}
if (years_xp != "") {
if ($(this).attr('data-xp') == years_xp) {
return true;
}
}
}).show();
});
我做错了什么?我已经卡在这个问题上将近6个小时了,看了其他的例子但是它们似乎不适用于我的情况。