开发者

How can I change the background image?

开发者 https://www.devze.com 2023-02-06 05:18 出处:网络
This sounds so easy to do and yet I can\'t seem to be able to do it. The idea is that when an \'a\' tag is clicked, check if it has a class called \'collapsed\'. If it does, change the \'ul\' backgrou

This sounds so easy to do and yet I can't seem to be able to do it. The idea is that when an 'a' tag is clicked, check if it has a class called 'collapsed'. If it does, change the 'ul' background (that the a tag is a part of). I don't know which 'a' tag was clicked so I don't know the id of the 'ul' that it is a part of... I thought I could drill up to find the parent 'ul' but it is not working.

HTML:

<ul class="some-class" id="some-id-1">  
   <a href="#" id="id-1">something</a>
   <li>  
      <a class="collapsed">something else</a>  
   </li>  
</ul>  

<ul class="some-class" id="some-id-2">  
   <a href="#" id="id-2">something</a>
   <li>  
      <a class="collapsed">something else</a> 开发者_如何学JAVA 
   </li>  
</ul>  

<ul class="some-class" id="some-id-3">  
   <a href="#" id="id-3">something</a>
   <li>  
      <a class="collapsed">something else</a>  
   </li>  
</ul>  

my script:

$('a').click(function() {  
   var cName = this.className;  
   switch(cName) {
      case 'collapsed' :
         $(this).parent().find('> ul').css('background','url(img/red.png) 0 0');
      break;
   };
});  

What am I doing wrong? Any and all suggestions are welcome...


Try using JQuery's closest function this way -

$('a').click(function() {  
   var cName = $(this).attr('class');  
   if(cName == 'collapsed') {
        $(this).closest('ul').css('background','url(img/red.png) 0 0');
   };
});  


First thing, this should be used like $(this).

$('a').click(function() {
   // Change the first .collapsed element next to the clicked a
   $(this).next('.collapsed').css('background-color', 'url(img/red.png) 0 0');
});
0

精彩评论

暂无评论...
验证码 换一张
取 消