gpt4 book ai didi

javascript - 使用 jQuery 同时使用文本框和复选框过滤数据?

转载 作者:行者123 更新时间:2023-11-30 16:36:33 25 4
gpt4 key购买 nike

我想通过使用 jQuery 来过滤存储在段落中的景点:

  • 文本框,我在其中放置了 substring 吸引力开始于​​
  • 复选框,应仅显示特定类别的景点。当您勾选多个框时,它应该显示具有任何列出类别的项目。

我已经做到了,但是这些过滤器不能同时工作。一个过滤器会覆盖另一个过滤器的结果,因为它们作用于整个列表并分别对整个列表调用 show()hide()

HTML:

<h3>Search:</h3>
<div>
<input type="text" id="search-box" class="form-control" placeholder="Search">
</div>
<h3>Categories:</h3>
<div id="options" class="checkbox">
<label>
<input type="checkbox" rel="club">Club</label>
<label>
<input type="checkbox" rel="other">Other</label>
</div>
<div id="attractions" style="font-size: x-large">
<p class="club" style="display: block;"><a href="/TouristAttractions/1">Cocomo</a>
</p>
<p class="club" style="display: block;"><a href="/TouristAttractions/2">Princess</a>
</p>
<p class="club" style="display: block;"><a href="/TouristAttractions/3">Le Secret</a>
</p>
<p class="other" style="display: block;"><a href="/TouristAttractions/4">Wyspa piasek</a>
</p>
<p class="other" style="display: block;"><a href="/TouristAttractions/5">C# Operational Base</a>
</p>
</div>

Javascript:

$('div.checkbox').delegate('input[type=checkbox]', 'change', function() {

var $lis = $('#attractions > p').hide();
var $checked = $('input:checked');

if ($checked.length) {
($checked).each(function() {
$lis.filter('.' + $(this).attr('rel')).show();
}).find('input:checkbox').change();
} else {
$lis.show();
}
});

$('#search-box').keyup(function() {
var valThis = this.value.toLowerCase();

$('div#attractions > p').each(function() {
var text = $(this).text(),
textL = text.toLowerCase();
(textL.indexOf(valThis) === 0) ? $(this).show(): $(this).hide();
});

});

我想一定有某种方法可以同时取得结果。如果能给我指明正确的方向,我将不胜感激,甚至可能建议放弃此代码并使用一些过滤器插件?

最佳答案

我认为这可以干净利落地解决您的问题。解释在评论中。

//Triger filterAttractions when something changes.
$("#search-box, #options input").change(filterAttractions);
$("#search-box").keyup(filterAttractions);

function filterAttractions() {
//Get the text of the textbox.
var searchtext = $("#search-box").val();
//Get an array with the rel attributes of the checked checkboxes.
var categories = $("#options input:checked").map(function() {
return $(this).attr("rel");
}).get();
//Perform this once for every attraction.
$("#attractions p").each(function() {
var attraction = $(this);
//See if it has any of the checked categories.
var category = false;
for(i=0; i<categories.length; i++)
if(attraction.hasClass(categories[i]))
category = true;
//See if it starts with the right text.
var text = attraction.text().indexOf(searchtext) === 0
//Show or hide the attraction depending on the result.
attraction.toggle(category && text);
});
}

Fiddle .

关于javascript - 使用 jQuery 同时使用文本框和复选框过滤数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32629279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com