2012-11-02 43 views
0

假設有三類的JavaScript得到的類名

<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') 

引發上述錯誤。

任何人都可以解釋爲什麼發生了,我怎麼能得到我想要的?

感謝

回答

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|$)/); 
+2

或'this.className'。 – RobG

+0

@alex你能說一下,爲什麼'/(?:^ | \ s)world_ \ d +(?:^ | \ $)/'([根本不起作用](http://jsfiddle.net/) J22Ex /))而不是簡單的'/ world_ \ d + /'? – Engineer

+0

@Engineer這對我來說是一個巨大的失敗。我會解決它。 – alex

1

嘗試

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

請告訴我發生的事情是jQuery的each功能設置this是DOM元素,並且不會'prewrap'圍繞這個元素的jquery包裝。

所以就像亞歷克斯說過的那樣,簡單地將它包起來會讓你想要你想要的東西。

0

,僅保留world_類名,你需要做一個字符串替換和刪除使用$ .trim空格:

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