jquery filtered list select
I have completed this tutorial on 'Creating a “Filterable” Portfolio with jQuery' from nettuts+ and was wanting to tweek it a bit.
I would like to instead of clicking the top navigation and each category fi开发者_Go百科lters based on what was clicked, i want to click one 'Design' and if I click another 'CMS' they will show the items from both categories. When clicked again will turn that filter off and show whatever is selected.
so, in other words I want it to display what ever i select and I unselect by clicking the category again.
Below is the JS file I am using:
$(document).ready(function() {
$('ul#filter a').click(function() {
$(this).css('outline','none');
$('ul#filter .current').removeClass('current');
$(this).parent().addClass('current');
var filterVal = $(this).text().toLowerCase().replace(' ','-');
if(filterVal == 'all') {
$('ul#portfolio li.hidden').fadeIn('slow').removeClass('hidden');
} else {
$('ul#portfolio li').each(function() {
if(!$(this).hasClass(filterVal)) {
$(this).fadeOut('normal').addClass('hidden');
} else {
$(this).fadeIn('slow').removeClass('hidden');
}
});
}
return false;
});
});
Any help on this would be great. Thanks.
Try maintaining an array of toggled elements. I can't test this, but its close I think.
EDIT: Now tested and working.
$(document).ready(function() {
$('ul#filter a').click(function() {
$(this).toggleClass('toggled_filter').parent().toggleClass('current'); // toggle a class for its state
$(this).css('outline','none');
var filterValList = [];
$('.toggled_filter').each(function(){
// add each text item to the list
filterValList.push($(this).text().toLowerCase().replace(' ','-'));
});
if($.inArray('all', filterValList) != -1 || filterValList.length === 0) {
$('ul#filter li:first').addClass('current');
$('ul#portfolio li.hidden').fadeIn('slow').removeClass('hidden');
} else {
$('ul#filter li:first').removeClass('current');
$('ul#portfolio li').each(function() {
var classes = $(this).attr('class').split(/\s+/);
// go through each of the classes on each element
// and hide them if they aren't toggled on
var match_found = false;
for(var i in classes){
if($.inArray(classes[i], filterValList) != -1) {
match_found = true;
}
}
// check and see if anything matched
if(!match_found){
$(this).fadeOut('normal').addClass('hidden');
} else {
$(this).fadeIn('slow').removeClass('hidden');
}
});
}
return false;
});
});
精彩评论