[英]jQuery dropdown menu toggle issue
When I click on open it toggles all of the submenus. 当我单击打开时,它将切换所有子菜单。 I want to toggle only the exact ul
under the li
. 我只想切换li
下的确切ul
。
$(document).ready(function(){ $(".has-children>a").click(function(event){ event.preventDefault(); }); $('.has-children').click(function() { $(this).find('>ul').toggle(300); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="menu"> <li class="has-children"> <a href="#">open</a> <ul class="submenu" style="display:none"> <li class="has-children"> <a href="#">open</a> <ul class="submenu" style="display:none"> <li>1</li> <li>2</li> <li>3</li> </ul> </li> </ul> </li> </ul>
You can achieve this by changing find()
to children()
to target only direct children of the li
. 您可以通过将find()
更改为children()
以仅将li
直接子对象作为目标来实现。
$(document).ready(function(){ $(".has-children>a").click(function(event){ event.preventDefault(); }); $('.has-children').click(function() { $(this).children('ul').toggle(300); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="menu"> <li class="has-children"> <a href="#">open</a> <ul class="submenu" style="display:none"> <li class="has-children"> <a href="#">open</a> <ul class="submenu" style="display:none"> <li>1</li> <li>2</li> <li>3</li> </ul> </li> </ul> </li> </ul>
This however causes a problem where clicking on children of children will close the menu, so instead you can use a
tag and the jQuery next()
function to toggle instead of children()
or find()
like this: 然而,这将导致这里点击孩子的孩子会关闭菜单的一个问题,所以不是你可以使用a
标签和jQuery的next()
函数来切换,而不是children()
或find()
是这样的:
$(document).ready(function() { $(".has-children>a").click(function(event) { event.preventDefault(); $(this).next().toggle(300); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="menu"> <li class="has-children"> <a href="#">open</a> <ul class="submenu" style="display:none"> <li class="has-children"> <a href="#">open</a> <ul class="submenu" style="display:none"> <li>1</li> <li>2</li> <li>3</li> </ul> </li> </ul> </li> </ul>
This also makes your script much shorter. 这也使您的脚本更短。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.