所以我试图在jquery中创建一个过滤器函数。但我不能让它正常工作。 所以这就是我想要做的事情
HTML
<div id="filter">
<div id="filters"></div>
<input id="search" type="text" value="" /> <a id="addFilter">ADD</a>
</div>
<ul>
<li class="log">Test 1</li>
<li class="log">Test 2</li>
<li class="log">Test 3</li>
<li class="log">Bla 1</li>
<li class="log">Blab 2</li>
<li class="log">Siawq 3</li>
</ul>
jQuery的:
//case insencitive :contains()
$.expr[":"].contains = $.expr.createPseudo(function (arg) {
return function (elem) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
//OnClick of add button, add filter to list, clear field
$("#addFilter").click(function () {
if($('input#search').val() != ""){
//filters.push();
$("#filters").append("<div>"+$('input#search').val()+"</div>");
$('input#search').val("");
}
});
//On Click of filter list item to remove filter
$("#filters").on('click',"div",function() {
$(this).remove();
$("input#search").change();
});
//Filter event on change and keyup
$("input#search").change(function () {
var filter = $(this).val();
if (filter) {
var matches = $("ul").find('li.log:Contains(' + filter + ')');
var obj = $('#filters > div');
var arr = $.makeArray(obj);
for(var i = 0;i<arr.length;i++){
var add = $("ul").find('li.log:Contains(' + arr[i].innerText + ')');
matches = $.extend(matches,add);
}
$("li.log").not(matches).slideUp();
matches.slideDown();
} else {
$("ul").find("li.log").slideDown();
}
return false;
})
.keyup(function () {
$(this).change();
});
答案 0 :(得分:1)
好一小时的摆弄,我找到了答案。
if (filter) {
var matches = $("ul").find('li.log:Contains(' + filter + ')');
var obj = $('#filters > div');
var arr = $.makeArray(obj);
for(var i = 0;i<arr.length;i++){
var add = $("ul").find('li.log:Contains(' + arr[i].innerText + ')');
matches = $.extend(matches,add);
}
$("li.log").not(matches).slideUp();
matches.slideDown();
}
应该是:
if (filter || arr.length != 0) {
if (filter) {
var matches = $("ul").find('li.log:Contains(' + filter + ')');
} else {
var matches = $();
}
for (var i = 0; i < arr.length; i++) {
matches = matches.add('ul li.log:Contains(' + arr[i].innerText + ')');
}
$("li.log").not(matches).slideUp();
matches.slideDown();
}