【发布时间】:2019-09-23 10:13:54
【问题描述】:
我有一个带有子菜单的导航菜单系统,如下例所示。在子菜单上(通过将鼠标悬停在“两级”上显示)是“仅执行 AJAX”选项。如果选择了该选项,将运行 ajax 例程,我希望下拉菜单立即再次隐藏(即,一旦单击该选项,子菜单就会消失)。
我尝试了 jQuery hide(),但这会永久禁用子菜单(即,将鼠标滑回菜单栏不会再次显示它)。
我也尝试了hide(),然后是show(),但这使得即使将鼠标移开后子菜单仍然可见。
mouseleave() 和 mouseout() 听起来很有希望,但无论我将它们应用于什么相关元素,它们似乎都没有做任何事情。
这是简化的代码:
$(function() {
$('.ajax').click(function(event) {
event.preventDefault(); //to keep from jumping to top of page
//$(this).closest('ul').hide(); /* this breaks the menu */
/* none of these do anything I can see */
$(this).mouseleave();
$(this).parent().mouseleave();
$(this).parent().parent().mouseleave();
$(this).trigger("mouseout");
$(this).parent().trigger("mouseout");
$(this).parent().parent().trigger("mouseout");
$(this).trigger("mouseleave");
$(this).parent().trigger("mouseleave");
$(this).parent().parent().trigger("mouseleave");
/* do stuff with AJAX */
});
});
ul.nav {
background-color:rgb(88,57,7);
list-style-type: none;
text-align: center;
vertical-align: middle;
min-height: 30px;
position:sticky;
top:0;
}
ul.nav li {
display: inline-block;
position: relative;
}
ul.nav-sub { /* second level menus */
display: none;
position: absolute;
background-color:rgb(88,57,7);
margin: -4px 0 0 15px;
border: 1px solid LightSteelBlue;
padding: 0;
border-radius: 0;
text-align: left;
min-height: 0;
}
ul.nav li:hover ul {
display: block;
z-index:100;
}
ul.nav-sub li {
display: block;
}
ul.nav a {
display: block;
color: LightSteelBlue;
padding: 10px 15px;
margin: 0;
font-family: arial, helvetica, sans-serif;
font-weight: bold;
text-decoration: none;
white-space:nowrap;
}
ul.nav a:hover {
background-color: rgb(132,78,12);
color: White;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<ul class="nav">
<li><a href="file1.php" target="_top">Simple</a></li>
<li>
<a href="#">Two-level ▼</a>
<ul class="nav-sub">
<li><a href="file2.php" target="_top">Go to a page</a></li>
<li><a class="ajax" href="#">Do AJAX only</a></li>
<li><a href="file3.php">Go to another page</a></li>
</ul>
</li>
</ul>
【问题讨论】: