如何找到一个带有类名的部分的div并获得该类名的剩余部分? [英] How to find a div with part of a class name and get remaining part of that class name?

查看:73
本文介绍了如何找到一个带有类名的部分的div并获得该类名的剩余部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面上有几个div,类 my_widget-2 my_widget-8 等等。
我可以用什么JavaScript或jQuery代码来获取数字2(即附加第一个匹配小部件的数字)?

There are several divs on my page with classes my_widget-2, my_widget-8, etc. What JavaScript or jQuery code can I use to get the number "2" (ie. the number that appends the first matching widget)?

注意:如果我再次写这个问题,我会改变这些类名的顺序,并想办法得到8,以避免给人一种我想要较小数字的印象。

Note: If I were to write this question again, I would change the order of these class names and ask for a way to get "8" in order to avoid giving the impression that I want the smaller number.

推荐答案

$( "[class*='my_widget']" ).each ( function () {
    var elClasses = $( this ).attr ( 'class' ).split ( ' ' );

    for ( var index in elClasses ) {
        if ( elClasses[index].match ( /^my_widget-\d+$/ ) ) {
            var classNum = elClasses[index].split ( '-' )[1];
            alert ( classNum );
            break;
        }
    }
} );

使用 attributeContains 选择器获取所有具有类 my_widget - * 的元素,然后循环遍历所有类的元素找你上课。找到后,提取数字部分。

Use the "attributeContains" selector to get all elements that have a class my_widget-*, and then loop trough all the classes the element has searching for you class. Once you find it, extract the number part.

这篇关于如何找到一个带有类名的部分的div并获得该类名的剩余部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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