【问题标题】:Get the last classname of an array with jquery使用 jquery 获取数组的最后一个类名
【发布时间】:2011-05-13 17:45:26
【问题描述】:

我想获取带有类名的数组的最后一项。我的代码是这样的

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

在控制台中我变成得到这个答案

["classname1 classname2"]

我怎样才能得到最后的班级名称?

谢谢

【问题讨论】:

  • 您的其他五个问题都没有得到可接受的答案?

标签: jquery split classname


【解决方案1】:
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 是否存在。

【讨论】:

  • @Peter 你真的应该关注@T.J。克劳德的建议并使用this.className 而不是.attr()。我刚刚在another thread 中提出了这一点。
  • @Stefan Mai 有点像。 var getClassName = "classname1 classname2".split(); alert(getClassName); 表明 split()使用空格作为默认拆分字符。编辑后很明显我不是唯一一个发现的人:)
【解决方案2】:

注意拆分的文档:

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

你需要写:

split(' ')

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

【讨论】:

    【解决方案3】:

    正如 jensgram 指出的那样,您就快到了;如果您想保持 jQuery 特定,请参阅他的详细回答。

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

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

    className property 的 DOM 元素受到所有主流浏览器(可能还有所有次要浏览器)的支持。

    不过,除非您在紧密循环中执行此操作,否则 $()attr 调用的额外开销可能并不重要。

    【讨论】:

    • @jensgram:哇,我几乎立刻就看到并解决了这个问题,谈谈时机。 :-)
    • @T.J.克劳德我冒昧地改变了我的性别:)
    • @jensgram:谢谢。你会笑,但我把“jensgram”读作“Jen's gram”,就像在“Jen's祖母”中一样,并且没有应用我的概率过滤器。 :-) 而且我敢肯定我们这里有几个祖母,但我认为没有那么多(可能更多的祖父)。
    • @T.J. Crowder :) 不过在这种情况下是CONCAT(<firstName>, <lastName>)
    • @jens 呵呵,@T.J. 其实不是第一次了。性别搞错了!热闹的 cmets :)
    【解决方案4】:
    $(this).attr('class').split(' ').pop()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-10
      • 2022-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      相关资源
      最近更新 更多