2012-01-18 59 views
3

我有下面的代码,它显示了嵌套的ul并在点击时隐藏了其他打开的ul。我的问题是我如何添加一个背景图像到父li,打开嵌套的ul,并从它关闭的父母李a删除背景图像?如何使用jquery添加/删除类或样式

这里是我的jQuery:

$(document).ready(function() { 
    $('ul ul').hide(); 

    $('ul li > a').click(function(event) { 
     $('ul ul').hide('slow'); 


     $(this).parent().find('ul').show('slow'); 
    }); 

});; 
+0

在jQuery中添加样式或类使用addClass/removeClass或css – 2012-01-18 15:53:49

+0

jQuery具有称为.addClass()和.removeClass()的方法,您只需调用.addClass('classNameHereWithTheQuotes') – laymanje 2012-01-18 15:59:58

回答

5
$('#item').addClass('myClass'); //will add the class 
$('#item').removeClass('myClass'); //will remove the class 


$('#item').toggleClass('myClass'); //will toggle the class (add it if doesn't have it or remove it if it does) 

和内嵌样式

$('#item').css({'color':'red','background':'blue'}); //will override those properties 
2

如果我理解正确的话,你可以抓住父li与母函数,然后设置一个背景图片与CSS功能

$('ul li > a').click(function(event) { 
    $(this).parent("li").css("background-image", "url('foo.png')"); 
});