我的JavaScript菜单存在一个小问题。
当我选择一个项目时,它始终显示最后一个子菜单。
对于Javascript专业人士来说,这非常简单:p
以下是样本:
ul#midnav {
border-width: 1px 0;
list-style: none;
margin-bottom: 5px;
text-align: center;
border-bottom: solid thin #c8c8c8;
padding: 0px 0px 13px 0px;
}
ul#midnav li {
display: inline;
padding: 0px 0px;
}
ul#midnav li a {
text-transform:uppercase;
font-size:11px;
padding: 5px 13px 0px 5px;
background: url('../image/arrow-topdown-gray.png') 100% 9px no-repeat;
}
ul#midnav li ul {
line-height: 28px;
padding: 0;
position: absolute;
top: -30px;
background: none;
display: none;
/* --Hide by default--*/
width: 960px;
height:28px;
background: #fff;
border-top: solid thin #eeeeed;
}
ul#midnav li ul a {
background: url('../image/arrow-left-gray.png') 100% 9px no-repeat;
}
<div id="navigation">
<div id="mid-nav">
<ul id="midnav">
<li><a href="#">Item 1</a>
<ul>
<li><a href="#">Item 1.1</a>
</li>
<li><a href="#">Item 1.2</a>
</li>
</ul>
</li>
<li><a href="#">Item 2</a>
<ul>
<li><a href="#">Item 2.1</a>
</li>
<li><a href="#">Item 2.2</a>
</li>
</ul>
</li>
<li><a href="#">Item 3</a>
<ul>
<li><a href="#">Item 3.1</a>
</li>
<li><a href="#">Item 3.2</a>
</li>
</ul>
</li>
<li><a href="#">Item 4</a>
<ul>
<li><a href="#">Contact Us</a>
</li>
<li><a href="#">Item 4.1</a>
</li>
<li><a href="#">Item 4.2</a>
</li>
</ul>
</li>
<li><a href="#">Item 5</a>
<ul>
<li><a href="#">Item 5.1</a>
</li>
<li><a href="#">Item 5.2</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
$(document).ready(function () {
$('ul#midnav li a').on('click', function (event) {
event.preventDefault();
$('#mid-nav > ul').find('ul').slideUp(function () {
$(this).closest('li').find('ul').slideToggle();
});
});
});
答案 0 :(得分:0)
this
处理程序中的 ready
引用了错误的对象:
$(document).ready(function () {
$('ul#midnav li a').on('click', function(event){
event.preventDefault();
var e=this;
// must alias or 'this' will refer to
// the last submenu slid into hiding
// instead of the one to open
$('#mid-nav > ul').find('ul').slideUp(
function(){
$(e).closest('li').find('ul').slideToggle(); // 'e' instaed of 'this'
});
});
});