简体   繁体   English

jQuery切换背景色

[英]Jquery toggle background color

I have a jquery function that when a li is clicked, the li expands. 我有一个jquery函数,当单击li时,li扩展。 That part is working fine. 那部分工作正常。 Now, I want, when the li is clicked it toggles a background color. 现在,我想要单击li时切换背景颜色。 But it works, however when i have to click on the li item again to untoggle the background color. 但是它有效,但是当我不得不再次单击li项来取消切换背景色时。 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> -s设置为默认颜色,并突出显示当前颜色:

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

... ...

UPDATE UPDATE

http://jsfiddle.net/NXVhE/4/ 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>都是同级的,执行这样的操作会稍微更有效,并且允许同一页面上的多个列表相互独立运行(同样,假设这是所需的功能)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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