I have this snippet (below) of jQuery that adds a separate CSS Selector for each of my elements with a class of '.filter-name' This works and i am happy with what it does.

jQuery('.filter-name').each(function(i){
                jQuery(this).addClass('title'+(i+1));
            });

My problem is that I have to fire a 'clicked' class every time each of the elements is clicked, which is done by the code below, it works but it doesn't look very elegant in the code. is there any way of refining this?

jQuery('.title1').click(function(){
            jQuery('.title1').toggleClass('clicked');
        });
        jQuery('.title2').click(function(){
            jQuery('.title2').toggleClass('clicked');
        });
        jQuery('.title3').click(function(){
            jQuery('.title3').toggleClass('clicked');
        });
        jQuery('.title4').click(function(){
            jQuery('.title4').toggleClass('clicked');
        });
        jQuery('.title5').click(function(){
            jQuery('.title5').toggleClass('clicked');
        });
        jQuery('.title6').click(function(){
            jQuery('.title6').toggleClass('clicked');
        });

I have tried :

jQuery('.title1, .title2, .title3, .title4, .title5, .title6').click(function(){
                jQuery('.title1, .title2, .title3, .title4, .title5, .title6').toggleClass('clicked');
            });

but this just fires all of them at the same time, which is not what I want the jQuery to do.

p.s using jQuery in noConflict(); hence the jQuery selector.

有帮助吗?

解决方案

How about adding the click handler to .filter-name,

jQuery('.filter-name').click(function () {
   //using this ensure that is toggling the correct element
   jQuery(this).toggleClass('clicked'); 
});

其他提示

Your solution would work like this,

jQuery('.title1, .title2, .title3, .title4, .title5, .title6').click(function(){
            jQuery(this).toggleClass('clicked');
});

I would suggest you to give class names for all titles as .title then you could reduce the code to,

jQuery('.title').click(function(){
            jQuery(this).toggleClass('clicked');
});

Delegate your event handling:

jQuery(document.body).on('click', '.filter-name', function() {
    jQuery(this).toggleClass('clicked');
});

You're already relying on .filter-name to generate all the .title# classes, so just use it to attach your event handler.

You should replace document.body with the lowest common ancestor for all your .filter-name elements.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top