Jquery 防止在单击菜单项时关闭下拉列表
我使用的是引导程序4 alpha6。下面是我的下拉列表html:Jquery 防止在单击菜单项时关闭下拉列表,jquery,html,twitter-bootstrap,bootstrap-4,Jquery,Html,Twitter Bootstrap,Bootstrap 4,我使用的是引导程序4 alpha6。下面是我的下拉列表html: <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" type="button" id="dropdownMenu2" aria-haspopup="true" aria-expanded="false"> Dropdown </button>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" type="button" id="dropdownMenu2" aria-haspopup="true" aria-expanded="false">
Dropdown
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenu2">
<h6 class="dropdown-header">
<input class="form-control form-control-sm" type="text" placeholder="Search">
</h6>
<button class="dropdown-item" type="button">Action</button>
<button class="dropdown-item" type="button">Another action</button>
<button class="dropdown-item" type="button">Something else here</button>
</div>
</div>
在脚本文件中,您正在下拉菜单类中查找p标记,但没有任何p标记。试着写: ```
```您需要使用以下事件,而不是单击: :调用hide实例方法后,立即触发此事件 单击按钮时,可以将数据属性设置为下拉列表以保存状态。开始时,可以将此值设置为false。最后,当下拉列表隐藏时,您可以测试该值并重置状态 此事件必须附加到您的下拉列表元素:
$('.dropdown-menu button').on('click', function(e) {
$('.dropdown').data('canBeClosed', true);
})
$('.dropdown').data('canBeClosed', false);
$('.dropdown').on('hide.bs.dropdown', function (evt) {
console.log('Event fired: ' + evt.type);
if ($('.dropdown').data('canBeClosed') == false) {
evt.preventDefault();
} else {
$('.dropdown').data('canBeClosed', false);
}
})
$('.下拉菜单按钮')。在('单击')上,函数(e){
$('.dropdown').data('canBeClosed',true);
})
$('.dropdown').data('canBeClosed',false);
$('.dropdown').on('hide.bs.dropdown',函数(evt){
if($('.dropdown').data('canBeClosed')==false){
evt.preventDefault();
}否则{
$('.dropdown').data('canBeClosed',false);
}
})
下拉列表
行动
另一个动作
还有别的吗
您是否尝试过事件停止播放
?或者event.stopImmediatePropagation
?我尝试了stopPropagation
,但没有尝试另一个。“让我也试一下。”卡莱仍然有同样的问题。问题是我也没有看到console.log输出..这是我的输入错误,我已经纠正了它。是的,但是当你点击按钮时,你不能关闭它。下拉切换
。这不是我想要的。当您在.dropdown
之外单击或单击.dropdown切换按钮时。谢谢。在我发布之前,我尝试了你在这里展示的内容,但没有成功。所以从那以后我就不知道了,来到这里慢慢来,没问题。@hobby coder回答并更新代码片段。我希望它能像你期望的那样工作
$('.dropdown-item').on('click', function (event) {
console.log(event)
event.preventDefault();
})
$('.dropdown-menu button').on('click', function(e) {
$('.dropdown').data('canBeClosed', true);
})
$('.dropdown').data('canBeClosed', false);
$('.dropdown').on('hide.bs.dropdown', function (evt) {
console.log('Event fired: ' + evt.type);
if ($('.dropdown').data('canBeClosed') == false) {
evt.preventDefault();
} else {
$('.dropdown').data('canBeClosed', false);
}
})