简体   繁体   中英

Jquery toggle background color

I have a jquery function that when a li is clicked, the li expands. That part is working fine. Now, I want, when the li is clicked it toggles a background color. But it works, however when i have to click on the li item again to untoggle the background color. Can someone assist me in the right direction on how to achieve this.

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

On every click set your <li> -s to default color and highlight the current:

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

Assuming the <li> s are all siblings, it would be slightly more efficient to do something like this, and would allow for more than one list on the same page to function independently of one another (again, assuming that is the desired functionality)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM