我正在尝试创建过滤功能,用户可以在输入框中输入文本,该功能将在用户输入时显示/隐藏数据。此外,它需要组合两个或多个单词,但仅用于显示具有该单词组合的结果,而不是显示可以找到单词的数据(因为该功能目前正在工作)。我试图创造这个时间,我不知道该怎么做。
这是最后一个有效的代码(JS Fiddle demo):
HTML:
<div class="gallery-search">
<input type="text" name="input-filter" class=form-control id="input-filter" placeholder="Search Here">
</div>
<div>
<a class="gallery" data-tags="chaos board nordic viking warriors display ship dock warhammer fantasy"></a>
<a class="gallery" data-tags="modular necron obelisk pyramid ziggurat scenery gaming board wasteland warhammer 40k"></a>
<a class="gallery" data-tags="modular nurgle imperial chaos gaming board toxic crossroad warhammer 40k"></a>
<a class="gallery" data-tags="modular necron obelisk pyramid ziggurat scenery warhammer 40k"></a>
<a class="gallery" data-tags="ork orc fort fortress modular palisade wood skaven scenery warhammer fantasy"></a>
</div>
JS:
var inputFilter = $('#input-filter');
inputFilter.on('keyup', function() {
var
$this = $(this),
search = $this.val().toLowerCase(),
words = search.split(/\s+/),
data;
if(search.length > 2){
$('.gallery').hide();
$('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) {
return data.indexOf(word) > -1;
});
}).show();
}
if(search == ''){
$('.gallery').show();
}
});
答案 0 :(得分:1)
return words.reduce(function(previousValue, currentValue, index, array) {
return previousValue && data.indexOf(currentValue) > -1;
},true);
http://jsfiddle.net/911hx0bd/5/
最后的true是init值,它是数组中第一个值的previousValue