jquery nav bar slidetoggle issue
I'm fairly new to jquery and so far i have got my code to toggle and slide a html menu. heres my code
<script type="text/javascript">
$(document).ready(function () {
$('li').each(function(){
$('li.menuheader').hover(function(){
$('ul.submenu').slideToggle('slow', function(){})
});
});
});
</script>
</head>
<body>
<div id="navbar">
<ul>
<li class="menuheader"开发者_开发知识库>test1
<ul class="submenu">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
</ul>
</li>
<li class="menuheader">test2
<ul class="submenu">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
</ul>
</li>
<li class="menuheader">test3
<ul class="submenu">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
</ul>
</li>
</ul>
</div>
</body>
</html>
my jquery dropdowns every menu everytime the mouse hovers over a menuheader. I need to seperate these out without using div id's and making seperate jquery functions. Can anyone help me with how to do this?
Maybe this is what you are looking for (n need to use slideToggle i think):
$('ul.submenu').hide();
$('li').each(function() {
$('li.menuheader').hover(function() {
$(this).find('ul.submenu').show('slow')
}, function() {
$(this).find('ul.submenu').hide('slow')
});
});
fiddle here: http://jsfiddle.net/DRjPF/
$('li.menuheader')
==> this will select all the menuheaders
. Filter them with this
.
$(document).ready(function () {
$('li').each(function(){
$(this).('menuheader').hover(function(){
$(this).children('ul.submenu').slideToggle('slow', function(){
....
})
});
});
});
Your code shows all ul.submenu
because they all match the selector. Use $(this).find('ul.submenu')
to find the appropriate ones for each li
.
Secondly, for each li
you bind a hover
handler for each li.menuheader
. That's unnecessary.
Also, hover
triggers at mouseenter and mouseout. mouseenter
should suffice,
$(document).ready(function () {
$('li.menuheader').mouseenter(function() {
$('ul.submenu').not(this).slideUp('slow'); // hide all
$(this).find('ul.submenu').slideDown('slow'); //
});
});
http://jsfiddle.net/zRvLt/
精彩评论