javascript获取类名

javascript获取类名,javascript,jquery,html,Javascript,Jquery,Html,假设有三个类 <div class="hello world_1"></div> <div class="hello world_2"></div> <div class="hello world_3"></div> 收到错误消息,说: TypeError: Object #<HTMLDivElement> has no method 'attr' 工作时 $('.hello')[0].attr('class

假设有三个类

<div class="hello world_1"></div>
<div class="hello world_2"></div>
<div class="hello world_3"></div>
收到错误消息,说:

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

$('.hello')[0].attr('class')
引发上述错误

有谁能解释一下为什么会这样,我怎样才能得到我想要的


谢谢

你需要把这个包起来,就像这样

$('.hello').each(function(){
  $(this).attr('class');
});
jQuery提供了
这个
作为对本机DOM元素的引用。要能够对其调用jQuery方法,请使用jQuery构造函数包装它

如果您想匹配模式的类
world\u n
,您可以使用

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


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


因此,正如alex所说,只需再次包装它,即可获得所需的名称。

要仅获取
world
类名,需要使用$替换字符串并删除空格。trim:

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

@亚历克斯,你能详细解释一下,为什么
/(?:^^\s)world\ud+(?:^ ^ ^ ^ \$)/
()而不是简单的
/world\ud+/
?@工程师,这对我来说是一个巨大的失败。我会修好的。@alex我只是想知道,你为什么需要那个“复杂的东西”?@Engineer,这要看情况而定。您可能有另一个类,其中包含您不想匹配的
world\
var matches = $(this).attr('class').match(/(?:^|\s)world_\d+(?:\s|$)/);
$('.hello').each(function(){
  $(this).attr('class');
});
$('.hello').each(function(){
  $.trim($(this).attr('class').replace('hello', ''));
});