jQuery: Multiple selector issue
I am having problems showing divs where the div has three selectors I need to match on. These are typical:
<div class="pinfo draft sept-2010">...</div>
<div class="pinfo published 开发者_StackOverflow中文版feb-2011">...</div>
etc...
There is always pinfo
followed by review state (published or draft) and then time frame (month + year)
This is what I currently have:
// Hide all rows
$(".pinfo").hide();
// Now, show those rows where the selectors are in the filters built
for (idx in $cls)
{
console.log('filter: '+$cls[idx]);
$('.pinfo').filter($cls[idx]).show();
}
where $cls is an array of strings. The strings are class selectors built given then choices made by the user from an input form. For example:
$cls = [".Draft .sept-2011",
".Published .sept-2011"]
I am having problems showing divs where the div has three selectors I need to match on.
Any help is appreciated.
Thanks! Eric
- Don't use a
for..in
loop on an an array. Only use them on objects, and only withhasOwnProperty
. You can use jQuery's$.each
here to loop through the array. - The big problem. A selector like
".Draft .sept-2011"
says "find elements with the classsept-2011
that have an ancestor element with the classDraft
. You can combine multiple class selectors: what you want is.Draft.sept-2011
.
So your code might look like this:
$cls = [".Draft.sept-2011",
".Published.sept-2011"]
var $pinfo = $('.pinfo').hide();
$.each($cls, function(idx, val) {
$pinfo.filter(val).show();
});
Note that I've also cached the $('.pinfo')
selector call for the sake of performance.
Try this instead:
$('.pinfo').parent().find($cls[idx]).show();
精彩评论