2010-11-22 34 views
1

我想用類名得到數組的最後一個項。我的代碼看起來像這樣用jquery得到數組的最後一個類名

var getClassName = []; 
getClassName = $(this).attr('class').split(); 
console.log(getClassName); 

在控制檯我成爲得到這個答案

["classname1 classname2"] 

我怎樣才能得到最後的類名?

感謝

+4

您的其他五個問題都沒有收到可接受的答案嗎? – 2010-11-22 09:37:08

回答

2

由於jensgram指出,你快到了;如果你想保持特定的jQuery,請看他的答案。

但是,你正在做的瀏覽器做了很多額外的工作,這是其中的時候,你真的不需要jQuery的一個:

var getClassName; 
getClassName = this.className.split(' '); 
console.log(getClassName[getClassName.length-1]); 

DOM元素的className property被所有主流瀏覽器的支持(也可能是所有次要的)。

儘管如此,除非你在緊密循環中這樣做,$()attr調用的額外開銷可能並不重要。

+0

這將是'this.className.split('');'但偉大的一點。 – jensgram 2010-11-22 09:40:31

+0

@jensgram:哇,我幾乎馬上就看到並修復了這個問題,談論時間安排。 :-) – 2010-11-22 09:41:26

+0

@ T.J。 Crowder和我冒昧地改變我的性別:) – jensgram 2010-11-22 09:42:21

4
console.log(getClassName[getClassName.length-1]); 

Will do你需要一個參數傳遞給split()

var getClassName = $(this).attr('class').split(' '); 
var lastIndex = getClassName.length - 1; 
console.log(getClassName[lastIndex]); 

編輯:使用this.className
考慮使用this.className而不是$(this).attr('class')。這在other answers中提及。

Andy E對我們如何傾向於過度使用jQuery:Utilizing the awesome power of jQuery to access properties of an element做了很好的寫作。該文章特別對待使用.attr("id"),但問題與$(...).attr('className')this.className相同。

可以甚至使用

var getClassName = (this.className || '').split(' '); 

,如果你不相信.className存在。

+0

抓到我的回答:) – 2010-11-22 09:39:19

+0

很酷。謝謝,那是我需要的方式。 – Peter 2010-11-22 09:41:50

+0

@Peter你應該真的關注@ T.J。 Crowder的建議並使用'this.className'而不是'.attr()'。我剛剛在[另一個線程]中提到了這一點(http://stackoverflow.com/questions/4243554/jquery-if-checkbox-is-checked-do-this/4243575#4243575)。 – jensgram 2010-11-22 09:43:38

2
$(this).attr('class').split(' ').pop() 
+0

+1這是我想到的。 – alex 2010-11-25 17:36:55

相關問題