使用jQuery查找元素的动态类名 [英] Find dynamic classname of element with jQuery

查看:127
本文介绍了使用jQuery查找元素的动态类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的元素数量未知,例如:

I'm having a unknown number of elements like so:

<div class="item item-1"></div>
<div class="item item-2"></div>
<div class="item item-3"></div>

我想做的是检查每个项目是否具有以"item-"开头的类名.如果为true,则提取ID.像这样:

What I want to do, is check if each item has a classname starting with "item-". If true, then extract the id. Something like this:

$("container").each(function
    if ($(this).hasClassNameStartingWith("item-"))
        console.debug(theId);
);

这怎么可能?

提前谢谢!

推荐答案

在class属性上使用包含选择器:

Use the contains selector on the class attribute:

$('container[class*=" item-"]').each( function() {
    var classID = null;
    var classes = $(this).attr('class').split( ' ' );
    for (var i = 0, len < classes.length; i < len; ++i) {
        var class = classes[i];
        if (class.match( /^item-/ )) {
            classID = class.replace("item-",'');
            break;
        }
    }
    if (classID) {
        ... do something ...
    }
});

请注意,给定示例标记,请使用引号将空格包括在内.如果"item-N"类可能出现在列表的开头,并且您确定没有任何意外地与该字符串匹配的类,那么您也可以省略空格.

Note the use of quotes to include the space, given your sample mark up. You could also omit the space if the "item-N" class could appear at the beginning of the list and you were sure that there weren't any classes that would accidentally match that string.

更新示例,以显示如何提取类名称的标识符部分.

Updated example to show how to extract identifier portion of class name.

这篇关于使用jQuery查找元素的动态类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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