toggleclass和addclass之间的区别 [英] difference between toggleclass and addclass
问题描述
我正在使用jquery,并尝试在选择该表行时向该表添加一个类.
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).parents("tr").toggleClass("over", this.clicked);
由于某种原因,这在只有某些已经分配了类的实例中无效. 在我对任何故障排除都太疯狂之前,我将其更改为以下内容-
For some reason, that wasn't working in only some instances where there was already a class assigned. Before I went too crazy with any troubleshooting, I changed it to the following -
$(this).parents("tr").addClass("over", this.clicked);
这个新选项似乎工作正常.
This new option appears to be working fine.
我的问题是上面的一个选项是否比另一个更好.....我应该使用toggleClass而不是addClass,还是addClass足够?
My question is whether one option above is better than the other.....Should I be using toggleClass instead of addClass, or is addClass sufficient?
感谢您的任何想法.
推荐答案
addClass
就是这样做,将类添加到元素中.
addClass
does just that, adds the class to the element.
toggleClass
会执行该操作,切换类,将其删除(如果存在),否则将其添加,但是可以选择使用布尔值(true/false)来确定是否应添加对象(true)或已删除(错误).
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
可能对您不起作用,这是预期的行为.您在addClass
中传递的参数始终无效,因为它总是添加类.
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.
结论:
使用toggleClass
切换类,使用addClass
添加类.
Use toggleClass
for toggling classes, use addClass
for adding classes.
这篇关于toggleclass和addclass之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!