jquery - show/hide div based on multiple selections
I have a (php/html/jquery/css) page where i'm displaying tags at the top (e.g. green, white, fruit, vegetable)
On the page I have divs marked appropriat开发者_开发知识库ely with classes:
<div class="green fruit">apple</div>
<div class="green vegetable">broccoli</div>
etc.
I'd like to show/hide divs based on which tags have been toggled show/hide.
By default everything is shown. Clicking a tag at the top will toggle the corresponding divs.
The tricky part is to show divs if any of its classes are toggled to 'show' and hide if all of its classes are toggled to hide.
I'm probably making this harder than it needs to be. Thanks for your advice!
Assuming that you're using buttons to toggle the tags:
<button class="tag" id="toggle-fruit">Fruit</button>
<button class="tag" id="toggle-green">Fruit</button>
<button class="tag" id="toggle-vegetable">Fruit</button>
...
This should work:
var divCollection = $('div'),
// Gather all tags (store in array):
tags = $.map(divCollection, function(){
return this.className.split(' ');
}),
// Object to store enabled tags:
enabledTags = {};
toggleTags();
$('button.tag').click(function(){
var tag = this.id.split('-')[1];
enabledTags[tag] = !enabledTags[tag];
$(this).toggleClass('toggled'); // Maybe add some CSS?
toggleTags();
});
function toggleTags() {
// Hide all divs, then show those that have at least one
// tag present in the enabledTags object.
divCollection.hide().filter(function(){
// Return true if one of classes is found in enabledTags
return !!$.grep(this.className.split(' '), function(){
return enabledTags[this];
}).length;
}).show();
}
See demo: http://jsbin.com/omota
If you first hide, and then show, it should do the trick.
$('#my_divs div').hide();
var tags = ['fruit', 'orange'];
for(var k in tags){
$('#my_divs div.' + tags[k]).show();
}
精彩评论