2012-05-18 114 views
5

試圖檢查對象是否有類。似乎很簡單,但我無法讓它工作。這裏是我的代碼:jQuery:檢查對象是否有類

的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 #%[email protected] 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> 
+0

什麼是不工作? – CambridgeMike

+6

你是否需要圍繞'if'條件的括號? – CambridgeMike

回答

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

應該

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

當您查看瀏覽器的錯誤控制檯時,很容易發現這一點。 :-)

+0

謝謝!我將開始使用錯誤控制檯。 – colindunn

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'); 

}); 

希望這有助於完整的代碼..