我有这样的数据属性:
data-tags="chaos board nordic viking warriors display ship dock warhammer fantasy"
JS函数基于标签对容器进行基本过滤:
var inputFilter = $('#input-filter');
inputFilter.on('keyup', function() {
var
$this = $(this),
search = $this.val().toLowerCase();
if(search.length > 2){
$('.gallery').hide();
$("a[data-tags*=" + search + "]").show();
}
if(search == ''){
$('.gallery').show();
}
});
目前这仅适用于一项工作。当我尝试搜索两个或更多标签时,我得到0结果。我怎样才能使它工作? JS Fiddle Demo
答案 0 :(得分:0)
它仅适用于一个匹配,因为您提供了一个文字字符串,例如"chaos warriors"
,然后将其传递给属性值选择器,搜索该字符串("chaos warriors"
),而不是对于包含这两个字符串的元素("chaos"
和 "warriors"
)。
要单独搜索这两个字符串,我建议(尽管还没有尝试过):
inputFilter.on('keyup', function() {
var
$this = $(this),
search = $this.val().toLowerCase(),
// finding each of the words that are entered:
words = search.split(/\s+/),
// declaring the variable for later use:
data;
$('.gallery').hide();
// selecting all <a> elements with a "data-tags" attribute,
// then filtering that collection:
$('a[data-tags]').filter(function(){
// splitting the data-tags attribute to an array of words:
data = this.dataset.tags.split(/\s+/);
// looking to see if any of the words (from the value)
// are present in the array formed from the data-tags
// attribute, using Array.prototype.some() to iterate
// over the given array, returning a Boolean true or false:
return words.some(function (word) {
data.indexOf(word) > -1;
});
}).show();
});
参考文献: