5

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

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>
4

2 回答 2

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

应该

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

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

于 2012-05-18T17:22:11.143 回答
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');

});

希望这可以帮助..

于 2012-05-18T17:24:38.253 回答