Javascript 如果已单击父级,则 jQuery 显示子菜单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8232176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery show submenu if parent have been clicked
提问by iKaspars
Could some one please help with code.
有人可以帮忙写代码。
I want to show the submenu only when submenu parent is clicked.
我只想在单击子菜单父级时显示子菜单。
HTML
HTML
<ul>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a>
<ul class="sub-menu">
<li><a href="#">Submenu</a></li>
<li><a href="#">Submenu</a></li>
</ul>
</li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a>
<ul class="sub-menu">
<li><a href="#">Submenu</a></li>
<li><a href="#">Submenu</a></li>
</ul>
</li>
<li><a href="#">Item</a></li>
</ul>
So if you click on the parent submenu will show.
所以如果你点击父子菜单就会显示出来。
Here is fiddle link - http://jsfiddle.net/KhNCV/1/
这是小提琴链接 - http://jsfiddle.net/KhNCV/1/
回答by Rafay
$('.sub-menu').hide();
$("li:has(ul)").click(function(){
$("ul",this).slideDown();
});
http://jsfiddle.net/3nigma/KhNCV/2/
http://jsfiddle.net/3nigma/KhNCV/2/
OR
或者
$('.sub-menu').hide();
$("li:has(ul)").click(function(){
$("ul",this).toggle('slow');
});
回答by erimerturk
$('.sub-menu').hide();
$("a").click(function(){
$(this).parent().children("ul").toggle();
})
check out this link http://jsfiddle.net/KhNCV/6/
回答by Kato
Here's your example working. It's unclear why you need the a
tags, as you could use cursor: pointer in the CSS to make the li
appear clickable. I'll assume you want to do some spiffy hovering on them in IE that's CSS only? If not, you could simplify by removing them.
这是您的示例工作。目前还不清楚为什么需要这些a
标签,因为您可以在 CSS 中使用 cursor: 指针来使li
显示可点击。我假设你想在 IE 中对它们进行一些漂亮的悬停,这只是 CSS?如果没有,您可以通过删除它们来简化。
Instead of doing hide() on .submenu, you should use CSS (parsed with DOM instead of onReady/load).
而不是在 .submenu 上做 hide(),你应该使用 CSS(用 DOM 解析而不是 onReady/load)。
.sub-menu { display: none; }
And then here's you code to toggle the menus:
然后这里是你的代码来切换菜单:
$('ul li a').click(function() {
$(this).parent().find('ul.sub-menu').toggle();
return false;
});
回答by Paul Kearney - pk
$('li a').click(
function() {
$(this).next().slideToggle();
})
回答by ShankarSangoli
Try this
尝试这个
$(function(){
//Hide all the sub menus
$('.sub-menu').hide();
$("li:has(ul)").click(function(){
//Find the child ul and slideToggle
$(this).children("ul").slideToggle();
});
});