如何在 javascript/jquery 中删除一个类的所有实例? [英] How to remove all instances of a class in javascript/jquery?

查看:22
本文介绍了如何在 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 class m-active
  • Whatever you chain after this selector gets applied to all selected elements
  • Chaining the call with removeClass('m-active') removes class m-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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆