DOM:
<div class='myDiv' data-catid='1,2,3'></div>
<div class='myDiv' data-catid='4,5'></div>
<div class='myDiv' data-catid='1,5,7'></div>
<div class='myDiv' data-catid='8,9'></div>
<div class='myDiv' data-catid='2,3,4'></div>
JS:
var filters = [2, 4];
我想遍历 div
,并隐藏那些在它们的 data-catid
中没有两个类别 ID 的。
到目前为止我有这个:
$('.myDiv').each(function(i, el){
var itemCategories = $(el).data('catId').split(',');
// Do check and then hide with $(el).css('visibility', 'hidden')
// if doesn't contain both filter id's in 'itemCategories';
});
最佳答案
使用 filter()
方法以及 javascript Array#every
方法(或 Array#some
方法均可)。
var filters = [2, 4];
// get all elements with class `myDiv`
$('.myDiv')
// filter out elements
.filter(function() {
// generate array from catid attribute
var arr = $(this)
// get data attribute value
.data('catid')
// split based on `,`
.split(',')
// parse the string array, it's optional
// if you are not parsing then convert Number to
// String while using with indexOf
.map(Number);
// check all catid presents
return !filters.every(function(v) {
// check index of elements
return arr.indexOf(v) > -1;
});
// or with `some` method
// return filters.some(function(v) { return arr.indexOf(v) === -1; });
// hide the elements
}).hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='myDiv' data-catid='1,2,3'>1</div>
<div class='myDiv' data-catid='4,5'>2</div>
<div class='myDiv' data-catid='1,5,7'>3</div>
<div class='myDiv' data-catid='8,9'>4</div>
<div class='myDiv' data-catid='2,3,4'>5</div>
仅供引用:对于较旧的浏览器,请检查 polyfill option of every
method .
关于JavaScript 通过比较两个数组来过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39972283/