[英]Select only First UL Li in Jquery
I have a html code我有一个 html 代码
<ul id="menu1">
<li> //When Click this will fire Jquery event
<a href="">Some word</a>
<ul style="display:block;">
<li>Hello</li>
</ul>
</li>
<li> //When Click this will fire Jquery event
<a href="">Some word</a>
<ul style="display:block;">
<li>Hello</li>
</ul>
</li>
<li> //When Click this will fire Jquery event
<a href="">Some word</a>
<ul style="display:block;">
<li>Hello</li>
</ul>
</li>
</ul>
My Question is I want to fire my jquery code when i click the main UL LI element , i do not want to fire jquery for the inner UL LI.我的问题是我想在单击主 UL LI 元素时触发我的 jquery 代码,我不想为内部 UL LI 触发 jquery。 but some how no matter how i try, it will fire all LI , below is my jquery
但是无论我如何尝试,它都会触发所有 LI,下面是我的 jquery
$('#menu1 li').click(function () {
$(this).find('ul').toggle();
});
I also try #ul li , #ul li a .我也尝试 #ul li , #ul li a 。 but it seems like nothing work.
但似乎没有任何作用。 is it anyway to achieve what I need ?
无论如何要达到我所需要的吗?
You can use the child combinator selector ( >
) to only select the top level li
children of the #menu1
element.您可以使用子组合器选择器 (
>
) 仅选择#menu1
元素的顶级li
子项。 Try this:尝试这个:
$('#menu1 > li').click(function () {
$(this).find('ul').toggle();
});
Although note that your code does not match up with the description of what you're trying to achieve.尽管请注意,您的代码与您要实现的目标的描述不符。 You need to instead place the event handler on the
a
element within the top level li
, and amend the DOM traversal to find the related ul
to toggle it.您需要将事件处理程序放在顶级
li
的a
元素上,并修改 DOM 遍历以找到相关的ul
来切换它。 Also note that your HTML is invalid - you're missing the </li>
tags.另请注意,您的 HTML 无效 - 您缺少
</li>
标签。 Try this:尝试这个:
$('#menu1 > li a').click(function(e) { e.preventDefault(); $(this).parent().find('ul').toggle(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul id="menu1"> <li> <a href="">Some word</a> <ul> <li>Hello</li> </ul> </li> <li> <a href="">Some word</a> <ul> <li>Hello</li> </ul> </li> <li> <a href="">Some word</a> <ul> <li>Hello</li> </ul> </li> </ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.