开发者

Check if class is present w/jQuery

Is it possible to check if a certain class is present in an element and if yes, create a variable for my function?

<a href="#" id="clickMe"><span class="A open"></span>link</a>

For example if class open is present I will create a varialbe "close".

$(fu开发者_如何学编程nction ()
{
    $('#clickMe').click(function ()
    {
        // if "open"
        var myVar = 'close';
        // else 
        var myVar = 'open';
    });
});


yes, hasClass will do it:

var isOpen = $(this).hasClass('open') ? 'close' : 'open';

Note that with your specific example, you'll need something closer to:

var isOpen = $(this).find('span').hasClass('open') ? 'close' : 'open';

since this in your callback will refer to the A and your open class is on the SPAN


jQuery also has a toggleClass method that may or may-not be what you're looking for:

$(this).toggleClass('open');

For reference: jQuery documentation It's usually pretty quick to find what you're looking for.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜