我有以下结构:
<div class="Downloadscontainer">
<ul>
<li>level 1</li>
<li><a href="#">level 1</a>
<ul>
<li>level 2</li>
<li>level 2</li>
<li><a href="#">some page</a>
<ul>
<li>level 2</li>
<li>level 2</li>
</ul>
</li>
</ul>
</li>
</ul>
我试图在点击其父 li 时显示 ul,以下是我的 jquery
$(document).ready(function () {
$(".Downloadscontainer ul li ul").css("display", "none");
$(".Downloadscontainer li").each(function () {
$(this).click(function () {
if ($(this).children('ul').length > 0) {
$('.Downloadscontainer li ul').toggle();
}
});
});
});
因此,如果我点击级别 1 LI
,它会显示 UL
,然后如果我点击级别 2 LI
,它有 UL
也关闭了级别 1 LI
的 UL
;我希望它继续打开子 UL
。我怎样才能获得这个功能?
最佳答案
http://jsfiddle.net/TrueBlueAussie/ot0kxs0z/2/
$(".Downloadscontainer li").click(function (e) {
e.stopPropagation();
$(this).children('ul').toggle();
});
注意事项:
- 您不需要
each
将处理程序附加到 jQuery 中的多个元素。 - 您只需要阻止子点击传播到 DOM 中的父 LI
- 正如
@George
所建议的那样,您最好附加到 anchor 击。
采用 anchor 方法,我建议将以下内容作为 DOM 更改友好:
http://jsfiddle.net/TrueBlueAussie/ot0kxs0z/5/
$(".Downloadscontainer a").click(function (e) {
e.preventDefault();
$(this).closest('li').children('ul').toggle();
});
注意事项:
- 它会找到离点击的 anchor 最近的
LI
,然后向下钻取到子UL
(而不是通过next
导航,这需要一个已知的安排。 preventDefault
将阻止空白书签链接(在您的示例中为href="#"
)滚动到页面顶部。如果它们是完整链接,它们将停止导航,因此如果您添加页面链接,您可能需要额外检查。
例如,您可以检查链接是否为空白书签并允许其他链接正常触发:
http://jsfiddle.net/TrueBlueAussie/ot0kxs0z/7/
$(".Downloadscontainer a").click(function (e) {
if ($(this).attr("href") == '#') {
e.preventDefault();
$(this).closest('li').children('ul').toggle();
}
});
这个 fiddle 有一个到 Google 的外部链接,以及 #
链接。
关于javascript - 单击父 li 展开子 ul,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26423230/