使用jquery获取数组的最后一个类名

我想得到一个带有类名的数组的最后一项。 我的代码看起来像这样

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

在控制台中,我得到了这个答案

 ["classname1 classname2"] 

我怎么能得到最后一个class级名字?

谢谢

正如jensgram指出的那样,你几乎就在那里; 如果你想保持特定于jQuery,请查看他对细节的回答。

但是你正在让浏览器做很多额外的工作,这是你真的不需要jQuery的时候之一:

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

所有主要浏览器(可能还有所有次要浏览器)都支持DOM元素的className属性 。

尽管如此,除非你在紧密循环中这样做,否则$()attr调用的额外开销可能并不重要。

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

会这样做 , 你需要将参数传递给split()

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

编辑:使用this.className
考虑使用this.className而不是$(this).attr('class') 。 其他答案中提到了这一点。

Andy E对我们如何过度使用jQuery做了很好的写作: 利用 jQuery 的强大function来访问元素的属性 。 本文专门讨论了.attr("id")的使用,但$(...).attr('className')this.className的问题相同。

你甚至可以使用

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

如果您不确定.className存在。

 $(this).attr('class').split(' ').pop() 

请注意拆分文档:

http://www.w3schools.com/jsref/jsref_split.asp

你需要写:

 split(' ') 

没有分隔符“将返回整个字符串”