开发者

jQuery findClass and display what this class is?

I’m trying to find an element with the class “active” and then echo what other classes it has, and only select the start of the string.

HTML:

<div class="cmButtons">
 开发者_JAVA技巧   <ul>
        <li class="cmAuto_btn a active">Auto BTN</li>
        <li class="cmPro_btn a">Pro BTN</li>
        <li class="cmFocus_btn a">Focus BTN</li>
        <li class="cmBright_btn a">Bright BTN</li>
        <li class="cmLow_btn a">Low BTN</li>
        <li class="cmMotion_btn a">Motion BTN</li>
        <li class="cmCustom_btn a">Custom BTN</li>
    </ul>
</div>

CSS:

#result{background:#EEE;border:1px solid #CCC;margin:20px 0;height:30px;line-height:30px;width:500px;}

Javascript (with jQuery):

if($('.cmButtons ul li').hasClass("active")){
    var activeLi = $(this).attr("class");
    $('#result').html(activeLi);
}

Demo on JS Fiddle.

So, based on the fiddle;

The active element is: <li class="cmAuto_btn a active">Auto BTN</li>

jQuery should output the class as: cmAuto_btn a active

jQuery should then modify the string to render as cmAuto_btn

How can I do this?


You need to iterate over the set of matched elements with each. You can then split the class names on spaces, and get the first element of the resulting array:

$('.cmButtons ul li').each(function() {
    if($(this).hasClass("active")) {
       var firstClass = $(this).attr("class").split(" ")[0];
    } 
});

Here's an updated example.

And here's an alternative, due to comments below (still using each in case there are multiple elements with class active):

$('.cmButtons ul li.active').each(function() {
    var firstClass = $(this).attr("class").split(" ")[0];
});

You should probably use this one, unless you also need to do something with elements that do not have the active class, in which case you can use the above example with an else block.


$('.cmButtons ul li').each(function(){
    if($(this).hasClass("active"))
       {
       $('#result').html($(this).attr("class"));
       }
});

Working Example: http://jsfiddle.net/tGypJ/12/


in this part "this" not mean the Li but the document, because it is out of the jquery selector block, you can by approved in it when you print this alert(this.location). so try this

$('.cmButtons ul li').each(function(idx, val) {
    if(val.hasClass("active")) {
       var activeLi = val.attr("class").split(" ")[0];
       $('#result').html(activeLi);
    } 
});


Simple ? :

var activeClasses = $('.cmButtons ul li.active').attr('class');
$('#result').html(activeClasses);

Demo : http://jsfiddle.net/Mpqfy/


So you can use like :

var active = $('.cmButtons ul li.active');
var activeClasses = active.attr('class');
$('#result').html(activeClasses);

active.doSomething();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜