问题描述:

i am working on a menu where i want to add a class to parent menu items only through jquery. the code i wrote for it is working fine but only if the menu item dont have any child elements(drop down menu). now what changes should i make to add a class to parent items only on hover.

here is the html

<nav id="main-menu" style="display: block;">

<ul id="menu-nav_menu" class="nav sf-js-enabled">

<li class="menu-item cat-item">

<a href="http://localhost/carp/?page_id=45" class="sf-with-ul">

<span class="main_text">About CARP</span>

</a>

<ul class="sub-menu" style="display: none; visibility: hidden;">

<li id="menu-item-41" class="menu-item">

<a href="http://localhost/carp/?page_id=40">Vision</a>

</li>

</ul>

</li>

<li class="menu-item">

<a href="http://localhost/carp/?page_id=48" class="sf-with-ul">

<span class="main_text">Our Work</span>

</a>

<ul class="sub-menu" style="display: none; visibility: hidden;">

<li class="menu-item">

<a href="http://localhost/carp/?page_id=50">How To</a>

</li>

</ul>

</li>

<li class="menu-item">

<a href="http://localhost/carp/?page_id=79">

<span class="main_text">Gallery</span></a>

</li>

<li class="menu-item">

<a href="http://localhost/carp/?page_id=81">

<span class="main_text">Contact Us</span></a>

</li>

</ul>

</nav>

here is the jquery

$(document).ready(function(){

//to change the background image of previous closest menu item background

$("#main-menu ul#menu-nav_menu li a").hover(function(e) {

e.preventDefault();

var i = $("#main-menu ul li a span").index($(this).parent() );

$('#main-menu li a span').eq(i-1).addClass('mybg');

$("#main-menu ul li a").mouseout(function() {

$('#main-menu li a span').eq(i-1).removeClass('mybg');

});

});

网友答案:

I assume you want to highlight the main menu item when the hover event occurs on it or its children. Simplest way to do it is using CSS:

#menu-nav_menu > li:hover > a { background-color: #FF0000; }

CSS Fiddle


Since you want to do it using jQuery:

jQuery

$(function () {
    $('#menu-nav_menu > li').hover(function() {
        $(this).children('a').toggleClass('myBg');
    });
});

CSS

.myBg { background-color: #FF0000; }

jQuery Fiddle


Your structure for the hover event is incorrect, please refer to the jQuery API docs for the proper usage.

Here's the CSS Selectors spec for your reference.

网友答案:

this might not give you what you need.. but improving your jquery.. you don't need mouseout() there..

try this

$(document).ready(function(){

  //to change the background image of previous closest menu item background
  $("#main-menu ul#menu-nav_menu li a").hover(function(e) {
     e.preventDefault();
     var i = $("#main-menu ul li a span").index($(this).parent() );
     $('#main-menu li a span').eq(i-1).addClass('mybg');
  },function(){
     var i = $("#main-menu ul li a span").index($(this).parent() );
     $('#main-menu li a span').eq(i-1).removeClass('mybg');
  });


});
相关阅读:
Top