开发者

jquery find previous li and change css

开发者 https://www.devze.com 2023-01-19 00:18 出处:网络
I\'m trying to write up a script that will allow me to change the css of the previous li on hover. Here\'s the structure:

I'm trying to write up a script that will allow me to change the css of the previous li on hover.

Here's the structure:

<ul id="mainlevel">
  <li><a href="/" class="mainlevel" id="active_menu">Home</a></li>
  <li><a href="/" class="mainlevel">About Us</a></li>
  <li><a href="/" class="mainlevel">Products</a></li>
  <li><a href="/" class="mainlevel">Projects</a></li>
  <li><a href="/" class="mainlevel">Suppliers</a></li>
</ul>

Here's what I have so far:

jQuery("#mainlevel li a").hover(f开发者_Go百科unction() {
    jQuery(this).prev("li a").css("background", "#f0f");
  });

But it's not working.. Any help would be appreciated :)


The following seems to work:

$(document).ready(
  function() {
    $('li a').hover(
      function(){
       $(this).parent().prev('li').css('background-color','#f0f'); 
      }
      );
  }
  );

Albeit I haven't removed the background-colours when the li is no longer hovered-over.

Demo at: JS Bin.


Can you try this

jQuery(this).parent().prev("li").children("a").css("background", "#f0f");

I think the prev() methods works with only the siblings of the current element. that is why you have to get the parent of the current element and then get the prev element

0

精彩评论

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