difference between toggleclass and addclass

后端 未结 4 1012
無奈伤痛
無奈伤痛 2021-02-20 14:35

I am working with jquery and attempting to add a class to a table on the selection of that table row.

I was initially using the following code -

$(this)         


        
相关标签:
4条回答
  • 2021-02-20 15:02

    If addClass is working for you, then you should stick with it. The methods are meant for different purposes. addClass ensures that a particular class is present on an element, while toggleClass adds the class if it isn't there and removes it if it is.

    Check out the API reference for the full explanation of each method:

    • http://api.jquery.com/toggleClass/
    • http://api.jquery.com/addClass/
    0 讨论(0)
  • 2021-02-20 15:11

    Depends really. If you don't plan on removing the class, I'd stick with addClass. Naturally, toggleClass allows you to toggle classes.

    0 讨论(0)
  • 2021-02-20 15:12

    addClass does just that, adds the class to the element.

    toggleClass on the other hand does THAT, toggles the class, removing it if it's there, otherwise adding it, but optionally taking a boolean value (true/false) to determine if the object should be added (true) or removed (false).

    toggleClass probably wasn't working for you in the instances where this.clicked was false, which is expected behavior. The argument you're passing in addClass has no effect, since it ALWAYS adds the class.

    Conclusion:

    Use toggleClass for toggling classes, use addClass for adding classes.

    0 讨论(0)
  • 2021-02-20 15:13

    There's no need to pass a second argument to .addClass() - it will always add the class.

    If that's the behaviour you want, that's the right method.

    0 讨论(0)
提交回复
热议问题