jQuery 如何使用jquery获取类名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2882058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:29:04  来源:igfitidea点击:

How to get class name using jquery

jquery

提问by Nick Craver

Suppose I have an element like this:

假设我有一个这样的元素:

<div id="dv" class="red green blue">Something Here !!</div>

I used this:

我用过这个:

alert($('#dv').attr('class'));

But it gives me all three at the same time, I need individually probably stored in an array.

但它同时给了我所有三个,我需要单独存储在一个数组中。

How do I get each of those class names using jquery? Should be simple, right?

如何使用 jquery 获取每个类名?应该很简单吧?

回答by jAndy

var classNames = $('#dv').attr('class').split(' ');

if you just need to know if an element owns a class you might want to use

如果你只需要知道一个元素是否拥有一个你可能想要使用的类

if( $('#dv').is('.green') ){
    alert('its green!');
}

or

或者

if( $('#dv').hasClass('green') ){
    alert('its green!');
}

which is a derived function. Keep attention to the different notation

这是一个派生函数。注意不同的符号

".className" and just "className"

“.className”和“className”

回答by Nick Craver

There are a few ways depending on your objective (do you actuallyneed an array, might be a quicker method!).

有几种方法取决于您的目标(您是否真的需要一个数组,可能是一种更快的方法!)。

To get an array of the classes use .attr()and .split():

要获取类的数组,请使用.attr()and .split()

$('#dv').attr('class').split(' ') == ['red', 'green', 'blue']

To get the literal string use .attr():

要获取文字字符串,请使用.attr()

$('#dv').attr('class') == 'red green blue'

To check for a class use .hasClass():

要检查类使用.hasClass()

$('#dv').hasClass('red') == true

回答by mck89

The class is an attribute so you can do var classname=$("#dv").attr("class")then you can split it into an array with var array=classname.split(" ");

该类是一个属性,因此您可以这样做,var classname=$("#dv").attr("class")然后您可以将其拆分为一个数组var array=classname.split(" ");

回答by Starx

use this

用这个

alert($('#dv').attr('class'));

回答by meo

with attr()you can set or retrieve any attribute you want. If you have more then one class you can split the string that attr gives you back with split("separator"). Split gives you back an array. $.each(array, function(i, data){})allows you to do something for each value in a array. If you put that together this is the result:

attr()您可以设置或检索任何你想要的属性。如果您有多个班级,您可以将 attr 返回的字符串与split("separator"). Split 返回一个数组。 $.each(array, function(i, data){})允许您对数组中的每个值执行某些操作。如果你把它们放在一起,结果是:

$.each( $("#dv").attr("class").split(" "), function(i, data) {
    alert(data)
})

And here a demo with your code: http://jsfiddle.net/Cq5JD/

这里有一个带有您的代码的演示:http: //jsfiddle.net/Cq5JD/