我有一个引导程序下拉菜单:
<div class="dropdown>
<a class="dropdown-toggle" href="#" id="menu1" data-toggle="dropdown"><img src="@imagePath" class="img-circle dropbtn" alt="Product" style="width:30px;height:30px;" /></a>
<ul class="dropdown-menu" id="productDD" role="menu" aria-labelledby="menu1"></ul>
</div>
现在ul通过ajax调用在页面上加载产品。问题是,当我单击下拉列表中的任何产品时,下拉列表将关闭。但是我只想在ul以外的任何地方单击鼠标时关闭下拉菜单
答案 0 :(得分:0)
只需将此脚本放入您的代码中
<script>
$(document).click(function() {
$(".dropdown").removeClass('open');
});
</script>
答案 1 :(得分:0)
尝试这样的事情:
$(document).click(function(e) {
// get the clicked element
$clicked = $(e.currentTarget);
// if the clicked element is not a descendent of the dropdown
if ($clicked.closest('.dropdown').length === 0) {
// close the dropdown
$('.dropdown').removeClass('open');
}
});
答案 2 :(得分:0)
在 2021 年,您会这样做:
$('.dropdown').on({
"shown.bs.dropdown": function() { /* whatever you want to do when it fires */ },
"click": function(e) { // handles click event
console.log(e.target) // just to check which element is on top
if($('.dropdown-menu').is(e.target)) { // if dropdown is clicked
this.closable = false // do not close it
return;
} else {
this.closable=true; // else close it
}
},
"hide.bs.dropdown": function() { return this.closable; } // save state
});
}