我想用类名得到数组的最后一个项。我的代码看起来像这样用jquery得到数组的最后一个类名
var getClassName = [];
getClassName = $(this).attr('class').split();
console.log(getClassName);
在控制台我成为得到这个答案
["classname1 classname2"]
我怎样才能得到最后的类名?
感谢
我想用类名得到数组的最后一个项。我的代码看起来像这样用jquery得到数组的最后一个类名
var getClassName = [];
getClassName = $(this).attr('class').split();
console.log(getClassName);
在控制台我成为得到这个答案
["classname1 classname2"]
我怎样才能得到最后的类名?
感谢
由于jensgram指出,你快到了;如果你想保持特定的jQuery,请看他的答案。
但是,你正在做的浏览器做了很多额外的工作,这是其中的时候,你真的不需要jQuery的一个:
var getClassName;
getClassName = this.className.split(' ');
console.log(getClassName[getClassName.length-1]);
DOM元素的className
property被所有主流浏览器的支持(也可能是所有次要的)。
尽管如此,除非你在紧密循环中这样做,$()
和attr
调用的额外开销可能并不重要。
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
存在。
您的其他五个问题都没有收到可接受的答案吗? – 2010-11-22 09:37:08