jQuery - 在元素上找到最后一个类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11258346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:24:39  来源:igfitidea点击:

jQuery - find last class on the element

jqueryjquery-selectors

提问by Iladarsda

How to find last class on the element without knowing exact number of classes?

如何在不知道确切类数的情况下找到元素上的最后一个类?

Our element:

我们的元素:

 <div class="class-1 class-2 some-other-class"></div>

Normal approach with split will not work here, as we do not know the number of classes. Can we check the length of the .split(' ')?

正常的 split 方法在这里不起作用,因为我们不知道类的数量。我们可以检查 的长度.split(' ')吗?

var i = $('div').prop('class');
var j = i.split(' ')[x];

Any suggestions much appreciated.

任何建议非常感谢。

回答by lonesomeday

The simplest solution is to use pop, which accesses the last element in the array.

最简单的解决方案是使用pop,它访问数组中的最后一个元素。

var lastClass = $('div').attr('class').split(' ').pop();

Note that popalso removes the element from the array, but since you aren't doing anything else with it, that's not a problem.

请注意,这pop也会从数组中删除元素,但由于您没有对其进行任何其他操作,因此这不是问题。

回答by thecodeparadox

var classStr = $('div').attr('class'),
    lastClass = classStr.substr( classStr.lastIndexOf(' ') + 1);

DEMO

演示

As classStrcontains class names separated by a single space, so lastIndexOf(' ')will find the last spaceand make partition from there and give you the last classname.

由于classStr包含由单个 分隔的类名space,因此lastIndexOf(' ')将找到最后一个space并从那里进行分区并为您提供class姓氏。