我希望能够过滤具有多个数据属性的结果。请查看示例代码。当您选择"孟菲斯"或"卡多瓦"时,它应该显示"孟菲斯和科尔多瓦"。目前这不起作用。我应该如何处理这个问题?
以下是我的 HTML:
$('.filter').change(function() {
//on each click, refresh visible / hidden for each item
$('li.result').each(function(i, item) {
var city = $(this).data('city');
var visible = $('input.filter[data-city="' + city + '"]:checked').length > 0;
visible ? $(this).show() : $(this).hide();
});
//if no checkboxes are checked, show everything
if ($('input.filter:checked').length === 0) $('li.result').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<input class="filter" data-city="Memphis" type="checkbox" /> memphis
<input class="filter" data-city="Cordova" type="checkbox" /> cordova
<input class="filter" data-city="Bartlett" type="checkbox" /> bartlett
</p>
<ul>
<li class="result" data-city="Memphis,Cordova">Memphis and Cordova</li>
<li class="result" data-city="Memphis">Memphis</li>
<li class="result" data-city="Cordova">Cordova</li>
<li class="result" data-city="Bartlett">Bartlett</li>
</ul>
这可以解决问题:
$('.filter').change(function() {
//reset all classes (remove show class)
$('li.result').removeClass('show');
//loop over the filters
$('.filter:checked').each(function() {
//store the city of the filter in a string called 'city'
var city = $(this).data('city');
$('li.result').each(function() {
//check if the data attribute of the result contains the city string
//if it matches this filter, add the class 'show' to this result
$('.result[data-city*="' + city + '"]').addClass('show');
});
});
if ($('input.filter:checked').length === 0) {
//if no checkboxes are checked, show everything
$('li.result').show();
}
else {
//else hide everything
$('li.result').hide();
//and show only items that match (with class 'show')
$('li.result.show').show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<input class="filter" data-city="Memphis" type="checkbox" /> memphis
<input class="filter" data-city="Cordova" type="checkbox" /> cordova
<input class="filter" data-city="Bartlett" type="checkbox" /> bartlett
</p>
<ul>
<li class="result" data-city="Memphis,Cordova">Memphis and Cordova</li>
<li class="result" data-city="Memphis">Memphis</li>
<li class="result" data-city="Cordova">Cordova</li>
<li class="result" data-city="Bartlett">Bartlett</li>
</ul>