开发者

JQuery: how to access multiple css classes using .attr()?

I have the following:

<div id="unique" class="myclass xyz_345">...</div>

Question: How do I access what # is after xyz_, given that I have 2 css classes being applied to it? (In the exa开发者_开发技巧mple above, it would be the number 345).

I've tried the following, but it does work:

var num_after_xyz = $('unique').attr("class").substring(4);


var num_after_xyz = $('#unique').attr("class").match(/^.*_(\d+).*/);
alert(num_after_xyz[1]);

This regular expression should work.

It looks for anything, followed by _ and some digits, followed by anything.


Try something along these lines:

jQuery.fn.getClassNumber = function(classPrefix){
    var classes = this.attr('class').split(" ");
    jQuery.each(classes, function(i){
        if (classes[i].substring(0,classPrefix.length-1)==classPrefix){
            return classes[i].substring(classPrefix.length-1);
            }
        });
    return false;
    }

Then to get the number after the class prefix:

$('element').getClassNumber('xyz_');

I think this will work but I haven't tested it, give it a go!


I'm pretty sure that

var myString = $("#unique").attr("class")

is going to return "abc xyz_345". So then you could split that string on space:

var mySplitResult = myString.split(" ");

and iterate through the resulting array looking for something that starts with "xyz_" - and then taking the substring of that element.

var s;
for (s in mySplitResult){
     if(s.substring(0,4) == "xyz_"){
          var numberAfterXYZ = s.substring(4);
     }
}


Let's make a little plugin for this:

//
// ReplaceClass
//
// @param   regexp|substr       The old classname you are looking for
// @param   newSubStr|function  The new classname
// @see     https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
// @depends jQuery
// @author  @abernier
//
(function($) {
    $.fn.replaceClass = function(oldClass, newClass){
        return this.each(function(i, el){
            $(el).attr('class', function(index, attr){
                return attr.replace(oldClass, newClass);
            });
        });
    };
})(jQuery);

eg:

$('<div class="foo bar"></div>').replaceClass('foo', 'bar');
# => [div.bar.bar]

or with regexp:

$('<div class="foo-25 bar"></div>').replaceClass(/foo-[0-9]{2}/, 'foo-100');
# => [div.foo-100.bar]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜