2012-07-03 55 views
2

我有一個jQuery的函數,當li被點擊時,li會展開。那部分工作正常。現在,我想要點擊li時切換背景顏色。但是,它的工作原理,但是當我必須再次點擊李項目以解開背景顏色。有人能幫助我在正確的方向如何實現這一目標。jquery切換背景顏色

$(function() { 
    $('.a').click(function() { 
     var name = $(this).attr("name"); 
     var content = $('.content[name=' + name + ']'); 
     $('.content').not(content).hide('fast'); 
     $('.selected').css('background', 'yellow'); 
     content.slideToggle('fast'); 
    }); 

    $("li").click(function() { 
     $(this).toggleClass("highlight"); 
    }); 
});​ 
+0

什麼是你點擊切換'背景顏色? –

+0

我在列表項目上點擊 –

回答

2

每當用戶點擊設置你的<li> -s到默認的顏色,並強調當前:

$("li").click(function() { 
    $("li").removeClass("highlight"); 
    $(this).addClass("highlight"); 
}); 

...

UPDATE

http://jsfiddle.net/NXVhE/4/

$(function() { 
    $('.a').click(function() { 
     $(this).removeClass("highlight");  
     var name = $(this).attr("name"); 
     var content = $('.content[name=' + name + ']'); 

     $('.content').not(content).hide(); 
     content.toggle(); 
    }); 

    $("a").click(function() { 
     $("a").removeClass("highlight"); 

     if ($(".content").is(":visible")) { 
      $(this).addClass("highlight"); 
     } 
    }); 
}); 
+0

非常感謝。 –

+0

不客氣 –

2

假設<li> s都是兄弟姐妹,做這樣的事情會稍微高效一些,並且允許同一頁面上的多個列表獨立於另一個列表工作(同樣,假設這是所需的功能)

$('li').click(function() { 
    $('this').addClass('highlight').siblings().removeClass('highlight'). 
});