jQuery-在元素上找到最后一个类 [英] jQuery - find last class on the element

查看:82
本文介绍了jQuery-在元素上找到最后一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我们的元素:

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

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

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(' ') ?

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

任何建议,不胜感激.

Any suggestions much appreciated.

推荐答案

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

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

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

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

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

这篇关于jQuery-在元素上找到最后一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆