簡體   English   中英

jQuery切換背景色

[英]Jquery toggle background color

我有一個jquery函數,當單擊li時,li擴展。 那部分工作正常。 現在,我想要單擊li時切換背景顏色。 但是它有效,但是當我不得不再次單擊li項來取消切換背景色時。 有人可以在正確的方向上協助我實現這一目標。

$(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");
    });
});​

每次單擊時,將<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");
        }
    });  
});

假設<li>都是同級的,執行這樣的操作會稍微更有效,並且允許同一頁面上的多個列表相互獨立運行(同樣,假設這是所需的功能)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM