JQuery optimization for searching classes
I have some filters on the left. Each filter has an id. The id of that filt开发者_开发知识库er is used to filter some results that have the id of the filter in their classes.
Filters refer to characteristics of products.. example
<a id="filter_colorRED">RED</a>
...
<li id="item4" class="filter_colorBLUE">Blah Blah</li>
<li id="item5" class="filter_colorRED ">Blah Blah</li>
<li id="item6" class="filter_colorRED filter_colorBLACK">Blah Blah</li>
I am looking for the best method to find which filters should be disabled. Disabled filters should be these that dont exist in visible items' classes.
For example if colorBlue is applied RED and BLACK should be disabled because the only <li>
that has the BLUE class doesn't contain RED or BLACK.
My only thought is for each filter to check against results .hasclass(filter's id)
but I think that this is poor. Any other idea?
Simple approach:
$("a").click(function () {
$("li").hide().hasClass(this.id).show();
});
Optionally you can choose a variant:
$("a").click(function () {
var a = this;
$("li").toggle(function() { return $(this).hasClass(a.id); });
});
toggle()
accepts a function that returns true or false in order to show or hide an element. You could do some more complex calculations in the toggle()
function. If you just check for hasClass()
, the first approach is the better one.
精彩评论