作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想通过使用 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/
我是一名优秀的程序员,十分优秀!