我正在开发一个菜单,我只想通过 jquery 向父菜单项添加一个类。我为它编写的代码工作正常,但前提是菜单项没有任何子元素(下拉菜单)。现在我应该进行哪些更改才能仅在悬停时将类添加到父项。
这是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>
这是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');
});
});