jQuery:检查一个对象是否有类

时间:2012-05-18 17:20:16

标签: javascript jquery html css

尝试检查对象是否有类。看起来很简单,但我无法让它工作。这是我的代码:

的Javascript

$('ul.nav li').click(function(){    
    if $(this).hasClass('selected') {
        alert('This is selected!');
    }

    else {
        alert('This is not selected!');
    }
});

$('ul.nav li:first-child').addClass('selected');

HTML

<ul class="nav">
    <li>Who we work for</li>
    <li>Articles and interviews</li>
    <li>Job openings</li>
    <li>What the #%!$@ is Post Typography?</li>
</ul>

<ul class="content">
    <li>This is who we work for.</li>
    <li>These are articles and interviews.</li>
    <li>These are our job openings.</li>
    <li>This is some info about Post Typography.</li>
</ul>

2 个答案:

答案 0 :(得分:25)

if $(this).hasClass('selected') {

应该是

if($(this).hasClass('selected')){

当您查看浏览器的错误控制台时,可以很容易地看到这一点。 : - )

答案 1 :(得分:0)

包含

中的完整代码
$(document).ready(function(){

$('ul.nav li').click(function(){    
    if ($(this).hasClass('selected')) {
        alert('This is selected!');
    }

    else {
        alert('This is not selected!');
    }
});

$('ul.nav li:first-child').addClass('selected');

});

希望这会有所帮助..