【问题标题】:jQuery: Select only a class containing a string?jQuery:只选择一个包含字符串的类?
【发布时间】:2011-05-05 15:38:14
【问题描述】:

我目前正在使用它来获取页面上特定 HTML 位的类:

$(this).parent("div").attr('class')

但是 div 有多个类:current_status status_billed

我的最终目标是获取以status_ 开头的类并将其替换为不同的类名。

所以使用上面的 .parent() 函数,我可以选择我需要的 div,但我需要删除 status_billed 类并将其替换为,例如,status_completed(或多个其他类名)。

【问题讨论】:

    标签: javascript jquery css-selectors


    【解决方案1】:

    选择具有status_billed 类的divs:

    $(this).parent('div.status_billed')
    

    选择class属性包含status_的divs:

    $(this).parent('div[class*=status_]')
    

    这大概是您使用jQuery selectors 所能获得的最佳效果。你可以使用.filter()做得更好:

    $(this).parent('div').filter(function ()
    {
        var classes = $(this).attr('class').split(' ');
        for (var i=0; i<classes.length; i++)
        {
            if (classes[i].slice(0,7) === 'status_')
            {
                return true;
            }
        }
        return false;
    });
    

    ...但我不确定您为什么要这样做 - .parent() 最多返回 1 个元素。你的意思是.closest() 还是.parents()?

    【讨论】:

    • 啊,这是一个很好的电话,谢谢。我刚刚删除了我的帖子,所以他不会浪费时间走那条路。
    • 也可以使用返回类[i];而不是返回true;返回实际的 status_xxxx。
    • @Thomas:这不是 jQuery 的 filter() 的工作方式。 "For each element, if the function returns true, the element will be included in the filtered set; otherwise, it will be excluded."
    • 不确定我是否能很好地解释自己。我正在使用parent() 来选择我当前正在使用的元素的父 div。我不需要返回该类的所有 div。我可以选择我需要的 div,但我最终想看看以 status_ 开头的类的名称是什么,因为它可以是许多不同的名称。
    • @Matt Ball:没错,我的记忆力很差 :(。感谢您的指正...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-21
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 2011-09-22
    相关资源
    最近更新 更多