如何在 javascript/jquery 中删除一个类的所有实例? [英] How to remove all instances of a class in javascript/jquery?
问题描述
我有一个名为 .m-active 的类,它在我的 HTML 中多次使用.
I have this class called .m-active that is used multiple times throughout my HTML.
基本上我想要做的是当用户单击图像(没有 m-active 类)时删除该类的所有实例,并将 m-active 类添加到该图像.
Basically what I want to do is remove all instances of that class when a user clicks on an image (which does not have the m-active class) and add the m-active class to that image.
例如,在 Backgrid 行中,您可能有一个点击处理程序,如下所示:
For instance in a Backgrid row you might have a click handler as follows:
"click": function () {
this.$el.addClass('m-active');
}
但您还想从之前添加的任何行中删除该类,以便一次只有一行具有 .m-active 类
But you also want to remove that class from any rows to which it was previously added, so that only one row at a time has the .m-active class
有谁知道如何在 javascript/jquery 中做到这一点?
Does anyone know how this can be done in javascript/jquery?
推荐答案
使用 jQuery:
$('.m-active').removeClass('m-active');
说明:
- 调用
$('.m-active')
从包含类m-active
的文档中选择所有元素 - 在此选择器之后链接的任何内容应用于所有选定元素
- 使用
removeClass('m-active')
链接调用会从所有选定元素中删除m-active
类
- Calling
$('.m-active')
selects all elements from the document that contain classm-active
- Whatever you chain after this selector gets applied to all selected elements
- Chaining the call with
removeClass('m-active')
removes classm-active
from all of the selected elements
有关此特定方法的文档,请参阅:http://api.jquery.com/removeClass/一个>
For documentation on this specific method, see: http://api.jquery.com/removeClass/
用 jQuery 来掌握整个选择器的东西一开始是有挑战性的,但是一旦你掌握了它,你就会以非常不同的方式看待一切.我鼓励您查看一些优秀的 jQuery 教程.我个人建议查看 Codeacademy 的 jQuery 轨道:http://www.codecademy.com/tracks/jquery
Getting grasp of the whole selector thing with jQuery is challenging at first, but once you get it, you see everything in very different light. I encourage you to take a look into some good jQuery tutorials. I personally recommend checking out Codeacademy's jQuery track: http://www.codecademy.com/tracks/jquery
这篇关于如何在 javascript/jquery 中删除一个类的所有实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!