javascript获取类名

Yuj*_* Wu 0 html javascript jquery

假设有三个类

<div class="hello world_1"></div>
<div class="hello world_2"></div>
<div class="hello world_3"></div>
Run Code Online (Sandbox Code Playgroud)

我想基于"你好"获得班级名称"world_1","world_2"和"world_3".代码:

$('.hello').each(function(){
  this.attr('class');
});
Run Code Online (Sandbox Code Playgroud)

得到错误说:

TypeError: Object #<HTMLDivElement> has no method 'attr'
Run Code Online (Sandbox Code Playgroud)

我做了一点实验,发现了

$('.hello:first').attr('class')
Run Code Online (Sandbox Code Playgroud)

同时工作

$('.hello')[0].attr('class')
Run Code Online (Sandbox Code Playgroud)

提出上述错误.

任何人都可以解释它为什么会发生,我怎么能得到我想要的东西?

谢谢

ale*_*lex 8

你需要包装this,就像这样......

$('.hello').each(function(){
  $(this).attr('class');
});
Run Code Online (Sandbox Code Playgroud)

jQuery提供this了对本机DOM元素的引用.为了能够在其上调用jQuery方法,请使用jQuery构造函数进行包装.

如果你想匹配模式类world_n,你可以使用...

var matches = $(this).attr('class').match(/(?:^|\s)world_\d+(?:\s|$)/);
Run Code Online (Sandbox Code Playgroud)

  • 或者`this.className`. (2认同)