jQuery:只选择一个包含字符串的类? [英] jQuery: Select only a class containing a string?

查看:399
本文介绍了jQuery:只选择一个包含字符串的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用此方法获取页面上特定位的HTML的类:

I'm currently using this to get the class for a specific bit of HTML on the page:

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

div 有多个类别: current_status status_billed

抓取以 status _ 开头的类,并将其替换为不同的类名。

My end goal here is to grab the class that starts with status_ and replace it with a different class name.

$ c> .parent()函数,我可以选择我需要的div,但是我需要删除 status_billed 并用例如 status_completed (或其他一些类名)替换。

So using my .parent() function above, I'm able to select the div I need, but I then need to remove the status_billed class and replace it with, for example, status_completed (or a number of other class names).

推荐答案

选择具有 status_billed 类的 div

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

选择 class 属性包含 status _

Select divs whose class attribute contains status_:

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

这是关于你会得到最好的效果 jQuery选择器。您可以使用 .filter() 做得更好:

That's about the best you'll get with jQuery selectors. You can do better using .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()

这篇关于jQuery:只选择一个包含字符串的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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