Toggle the display of a ul submenu only if parent li is clicked
I've looked through some of the other questions on this site that I thought might help, like this one and this one, but they don't seem to answer my question. What I have is the following:
$(document).ready(function() {
$(".has-submenu ul").hide();
$(".has-submenu").click(function() {
$(this).children("ul").toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a href="#">Item 1</a></li>
<li class="has-submenu"><a href="#">Item 2</a>
<ul>
<li><a href="#">Sub Item 1</a></li>
</ul>
</li>
</ul>
您可以使用$(".has-submenu > a")
的点击来选择a
是直接孩子.has-submenu
只,然后使用next()
目标ul
$(".has-submenu ul").hide();
$(".has-submenu > a").click(function() {
$(this).next("ul").toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a href="#">Item 1</a></li>
<li class="has-submenu"><a href="#">Item 2</a>
<ul>
<li><a href="#">Sub Item 1</a></li>
</ul>
</li>
</ul>
您必须将选择器更改为$(".has-submenu>a")
并在点击时切换其.siblings("ul")
。
$(document).ready(function() {
$(".has-submenu ul").hide();
$(".has-submenu>a").click(function() {
$(this).siblings("ul").toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a href="#">Item 1</a></li>
<li class="has-submenu"><a href="#">Item 2</a>
<ul>
<li><a href="#">Sub Item 1</a></li>
</ul>
</li>
</ul>
即使.has-submenu
有多个项目,也是如此。
$(".has-submenu ul").hide();
$(".has-submenu > a").click(function() {
$(this).parent().find('ul').each(function(){$(this).toggle();});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a href="#">Item 1</a></li>
<li class="has-submenu"><a href="#">Item 2</a>
<ul>
<li><a href="#">Sub Item 1</a></li>
</ul>
<ul>
<li><a href="#">Sub Item 2</a></li>
</ul>
</li>
</ul>
链接地址: http://www.djcxy.com/p/91800.html
上一篇: 为什么我更改主题设置时会触发AdaptiveTrigger?
下一篇: 仅在单击父母li时才切换显示ul子菜单