Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

javascript - jQuery: Select only a class containing a string?

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

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

But that div has multiple classes: current_status status_billed

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

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Select divs that have the status_billed class:

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

Select divs whose class attribute contains status_:

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

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;
});

...but I'm not sure why you're doing all this - .parent() returns at most 1 element. Did you mean .closest() or .parents()?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...