And*_*ndy 2 optimization jquery
我正在尝试动态过滤搜索结果.每个结果都有与之关联的标签,用作类.
<div class="search_results">
<div class="html php jquery">
I can do HTML, PHP and JQuery.
</div>
<div class="jquery asp pascal">
I can do jQuery, ASP, and Pascal.
</div>
<div class="php basic webOS">
I am a PHP, Visual Basic, and WebOS expert.
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我想根据标签动态选择结果.我理解如何静态地执行此操作:
/* Hide all search results */
jQuery(".search_results div").hide();
/* Show everything with .php and .jquery tags */
jQuery(".search_results .php, .search_results .jquery").show()
Run Code Online (Sandbox Code Playgroud)
但是,我需要根据选中的复选框列表动态发生这种情况.
<div class="filters">
<input type="checkbox" value="php" />
<input type="checkbox" value="jquery" />
<input type="checkbox" value="webOS" />
etc..
</div>
Run Code Online (Sandbox Code Playgroud)
检查这些框后,我想过滤我的结果.
我的问题:我会用什么功能来做这件事?每个页面结果都有不同的标签集合.它会是这样的吗?
// Create new array
var filter_array = new Array();
// wait for a filter checkbox to be clicked
jQuery(".filters input").click(function() {
// Cycle through all input fields, and focus only on checked ones
jQuery('.filters input:checked').each( function() {
// Add current value to array
filter_array.push(jQuery(this).val());
});
// Now filter the results
for(i=0; i< filter_array.length;i++) {
// Hide all results
jQuery(".search_results div").hide(); /* Hide all search results */
// What do I do here to make sure elements that are dipslayed meet all the filter criteria?
}
});
Run Code Online (Sandbox Code Playgroud)
另外,我是否必须使用循环功能?有没有办法更快地做到这一点?假设我在一个页面上可以有多达50-100个结果元素.我对jQuery优化不太熟悉,所以我试图找到最有效的方法.
谢谢.
你可以这样做:
jQuery('.filters input:checked').each( function() {
// Add current value to array
filter_array.push(jQuery(this).val());
});
jQuery(".search_results div").hide().filter('.' + filter_array.join(',.')).show();
Run Code Online (Sandbox Code Playgroud)
这构造了一个类似的字符串.jquery,.php,.python,然后显示div匹配该一体化选择器的s.(请注意,我们已经将选择限制为,.search_results div因此我们不需要多次遍历文档来查找它们.)