我希望通过以下方式使用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();
});
});
我认为必须有某种方法来实现同步结果。我很高兴向我展示正确的方向,甚至建议删除此代码并使用一些过滤器插件?
答案 0 :(得分:2)
我认为这会以干净清晰的方式解决您的问题。解释在评论中。
//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);
});
}