javascript获取类名

时间:2012-11-02 06:08:53

标签: javascript jquery html

假设有三个班级

<div class="hello world_1"></div>
<div class="hello world_2"></div>
<div class="hello world_3"></div>

我希望基于“你好”获得班级名称“world_1”,“world_2”和“world_3”。代码:

$('.hello').each(function(){
  this.attr('class');
});

错误说:

TypeError: Object #<HTMLDivElement> has no method 'attr'

我进行了一些实验并找到了

$('.hello:first').attr('class')

工作时

$('.hello')[0].attr('class')

引发了上述错误。

任何人都可以解释为什么会发生这种情况,我怎样才能得到我想要的东西?

由于

4 个答案:

答案 0 :(得分:8)

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

$('.hello').each(function(){
  $(this).attr('class');
});

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

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

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

答案 1 :(得分:1)

$('.hello').each(function(){
  $(this).attr('class');
});

答案 2 :(得分:1)

发生的事情是jquery each函数将this设置为DOM元素,并且不会在该元素周围“预包裹”jquery包装。

就像亚历克斯所说的那样,再简单地包装就会让你想要你想要的东西。

答案 3 :(得分:0)

要仅获取world_类名,您需要使用$ .trim执行字符串替换并删除空格:

$('.hello').each(function(){
  $.trim($(this).attr('class').replace('hello', ''));
});