切换类和添加类之间的区别
我正在使用 jquery 并尝试在选择该表行时将类添加到表中。
我最初使用以下代码 -
$(this).parents("tr").toggleClass("over", this.clicked);
由于某种原因,该代码仅在某些已分配类的实例中不起作用。 在我对任何故障排除过于疯狂之前,我将其更改为以下内容 -
$(this).parents("tr").addClass("over", this.clicked);
这个新选项似乎工作正常。
我的问题是上面的一个选项是否比另一个更好......我应该使用toggleClass而不是addClass,还是addClass就足够了?
感谢您的任何想法。
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.
My question is whether one option above is better than the other.....Should I be using toggleClass instead of addClass, or is addClass sufficient?
thanks for any thoughts.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
addClass
就是这样做的,将类添加到元素中。另一方面,toggleClass 则执行此操作,切换类,如果存在则将其删除,否则添加它,但可以选择采用布尔值(true/false)来确定是否应添加该对象(true )或删除(假)。
在
this.clicked
为false
的情况下,toggleClass
可能不适合您,这是预期的行为。您在addClass
中传递的参数没有任何效果,因为它总是添加该类。结论:
使用
toggleClass
来切换类,使用addClass
来添加类。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 wherethis.clicked
wasfalse
, which is expected behavior. The argument you're passing inaddClass
has no effect, since it ALWAYS adds the class.Conclusion:
Use
toggleClass
for toggling classes, useaddClass
for adding classes.如果
addClass
适合您,那么您应该坚持使用它。这些方法用于不同的目的。addClass
确保元素上存在特定的类,而toggleClass
如果不存在则添加该类,如果存在则将其删除。查看 API 参考以获取每种方法的完整说明:
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, whiletoggleClass
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:
无需将第二个参数传递给 .addClass() - 它始终会添加该类。
如果这是您想要的行为,那么这就是正确的方法。
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.
真的要看情况。如果您不打算删除该类,我会坚持使用
addClass
。当然,toggleClass
允许您切换类。Depends really. If you don't plan on removing the class, I'd stick with
addClass
. Naturally,toggleClass
allows you to toggle classes.