在下面的菜单中,如果没有子菜单链接,我希望链接表现正常,否则父链接应该阻止默认,然后应该在submenu
上设置一个类,它将显示以前隐藏的子菜单项。问题是我不能让$(this).next(".submenu").toggleClass("opened");
工作,大概是因为它已经包含在引用$(this)
的条件中了。
小提琴here和下面的代码。提前谢谢。
<div class="wrap">
<ul>
<li>
<a href="http://test.com">top 1</a>
<ul class="submenu">
<li><a href="">sub 1</a></li>
<li><a href="">sub 2</a></li>
<li><a href="">sub 3</a></li>
</ul>
</li>
<li><a href="https://google.com">top 2</a></li>
<li><a href="https://google.com">top 3</a></li>
</ul>
</div>
.wrap .submenu {
display: none;
}
.submenu.opened {
display: block;
}
if (
$(".wrap ul li")
.has(".submenu")
.addClass("hasSubMenu")
);
$(".wrap ul li").click(function(e) {
console.log("a");
// we only want to target <li> that have a <ul> sub-menu
if ($(this).hasClass("hasSubMenu")) {
// first prevent default on the link
e.preventDefault();
console.log($(this));
// now find .submenu and add class
$(this)
.next(".submenu")
.toggleClass("opened");
} else {
console.log("test: no submenu");
}
});
发布于 2018-07-30 07:22:36
好的,我想我可能有答案了。在初始$(this)
中,我将内部$(this)
存储在一个var中。我不知道为什么这应该是有效的,但它似乎仍然有效。
if (
$(".wrap ul li")
.has(".submenu")
.addClass("hasSubMenu")
);
$(".wrap ul li").click(function(e) {
console.log("a");
// we only want to target <li> that have a <ul> sub-menu
if ($(this).hasClass("hasSubMenu")) {
var $this = $(this)
// first prevent default on the link
e.preventDefault();
console.log($(this));
// now find .submenu and add class
$this
.find(".submenu")
.toggleClass("opened");
} else {
console.log("test: no submenu");
}
});
https://stackoverflow.com/questions/51585274
复制相似问题