jQuery切换菜单点击问题
我只是想用 jQuery 创建一个简单的切换菜单,但无法完全正常工作。
在当前状态下,它不会滑动切换
HTML:
<ul id="menu">
<li><a href="one.html">One</a>
<ul>
<li><a href="one-one.html">one one</a></li>
<li><a href="one-two.html">one two</a></li>
<li><a href="one-three.html">one three</a></li>
</ul>
</li>
<li><a href="two.html">Two</a></li>
<li><a href="three.html">Three</a>
<ul>
<li><a href="three-one.html">three one</a></li>
<li><a href="three-two.html">three two</a></li>
<li><a href="three-three.html">three three</a></li>
</ul>
</li>
<li><a href="four.html">Four</a></li>
</ul>
JS:
$(document).ready(function() {
// Hide the sub menu items first
$("ul#menu > li > ul").hide();
// On click
$('ul#menu > li').click(function() {
// If there are sub items toggle them & prevent default click action
if ( ('ul#menu > li').has('ul').length > 0 ) {
$('ul#menu > li > ul').slideToggle("slow");
return false;
};
});
});
我需要它滑动切换,但也需要适当地处理点击,这样父列表项就不会点击,但子菜单项会点击进入其相关页面。
I'm just trying to create a simple toggle menu with jQuery but can't quite get it working.
In it's current state it doesn't slide toggle
HTML:
<ul id="menu">
<li><a href="one.html">One</a>
<ul>
<li><a href="one-one.html">one one</a></li>
<li><a href="one-two.html">one two</a></li>
<li><a href="one-three.html">one three</a></li>
</ul>
</li>
<li><a href="two.html">Two</a></li>
<li><a href="three.html">Three</a>
<ul>
<li><a href="three-one.html">three one</a></li>
<li><a href="three-two.html">three two</a></li>
<li><a href="three-three.html">three three</a></li>
</ul>
</li>
<li><a href="four.html">Four</a></li>
</ul>
JS:
$(document).ready(function() {
// Hide the sub menu items first
$("ul#menu > li > ul").hide();
// On click
$('ul#menu > li').click(function() {
// If there are sub items toggle them & prevent default click action
if ( ('ul#menu > li').has('ul').length > 0 ) {
$('ul#menu > li > ul').slideToggle("slow");
return false;
};
});
});
I need it to slide toggle but also handle the clicks appropriately so the parent list items don't click through but the sub menu items do click through to their relevant pages.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果我正确理解你的问题,这将满足你的要求:
你可以在这里测试它: http://jsfiddle.net/5fNbh /
更新:处理您在评论中指定的其他情况。
This will do what you want if I understand your question correctly:
You can test it here: http://jsfiddle.net/5fNbh/
Update: takes care of additional cases you specified in comments.
将
e.preventDefault() (并停止传播)添加到
将点击重新绑定到 或执行
(看到 现在返回 false 了吗?)
The
adds e.preventDefault() (and stop propagation) to the <li> instead of the <a> tag.
rebind the click to the <a> or do
(see the <a> is now getting the return false?)
这已经做过很多次了。查看这些链接:
This has been done a number of times. Check these links out: