2012-01-18 57 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')"); 
});