简体   繁体   中英

What is the best way to toggle a click event in javascript?

I have a FAQ page which questions open up to reveal answers and display a little plus or minus icon depending on weather the question has been click on to open or close it.

I can achieve this action by adding classes to the element which has been clicked to show weather it has been opened are not.

$( ".faq-question" ).click(function(){
    if(!($(this).hasClass("open"))){
        $(this).addClass('open');
        $('span.icon', this).html('-');
    }else{
        $(this).removeClass('open');
        $('span.icon', this).html('+');
    }
});

在此处输入图片说明

I'm wondering if there is a in-built toggle function for jQuery or JavaScript which aslo achieves this? I see that the jQuery toggle() event is depreciated and there are plenty of suggestions online on how to achieve this with custom scripts but what is the best way, is the method of adding classes to the HTML ok? Why was the toggle function removed? It seemed very useful.

Your approach works, but it has disadvantage is that JS code becomes obtrusive because of +/- symbols in it. Normally you don't want presentation to be mixed with javascript code. You can try this instead:

$( ".faq-question" ).click(function() {
    $(this).toggleClass('open');
});

And move presentation to CSS:

.faq-question .icon:after {
    content: '+';
}
.faq-question.open .icon:after {
    content: '-';
}

If tomorrow you want to use plus/minus icons instead of "+/-" chars, you will not need to touch javascript code at all.

Use .toggleClass in jquery

$( ".faq-question" ).click(function(){

        $(this).toggleClass('open');

        var symbol = ($(this).hasClass('open')) ? '-' : '+';

        $('span.icon', this).html(symbol);

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM