简体   繁体   English

在javascript中切换点击事件的最佳方法是什么?

[英]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? 我想知道是否有内置的jQuery或JavaScript切换功能可以实现此目的? 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? 我看到jQuery toggle()事件已被贬值,并且在线上有很多关于如何使用自定义脚本实现此目标的建议,但是最好的方法是什么,将类添加到HTML的方法可以吗? 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. 您的方法可行,但缺点是JS代码由于其中的+/-符号而变得难以理解。 Normally you don't want presentation to be mixed with javascript code. 通常,您不希望演示文稿与javascript代码混合在一起。 You can try this instead: 您可以尝试以下方法:

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

And move presentation to CSS: 并将演示文稿移至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. 如果明天您要使用加号/减号图标代替“ +/-”字符,则完全不需要触摸javascript代码。

Use .toggleClass in jquery 在jQuery中使用.toggleClass

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

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

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

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

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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