我正在使用Bootstrap 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-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>
我想要的是,当有人点击.dropdown-menu
内的任何项目时,不要关闭下拉列表。我写了下面的JS,但它没有工作,意味着仍然点击菜单项bootstrap下拉正在关闭。
<script type="text/javascript">
$(function() {
$('.dropdown-menu button').on('click', function (event) {
console.log(event)
event.preventDefault();
})
});
</script>
答案 0 :(得分:0)
在您的脚本文件中,您正在下拉菜单类中查找p-tag,但您没有任何p-tag。试着写: ```
$('.dropdown-item').on('click', function (event) {
console.log(event)
event.preventDefault();
})
```
答案 1 :(得分:0)
您需要使用以下活动,而不是点击:
hide.bs.dropdown:调用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);
}
})
$('.dropdown-menu button').on('click', function(e) {
$('.dropdown').data('canBeClosed', true);
})
$('.dropdown').data('canBeClosed', false);
$('.dropdown').on('hide.bs.dropdown', function (evt) {
if ($('.dropdown').data('canBeClosed') == false) {
evt.preventDefault();
} else {
$('.dropdown').data('canBeClosed', false);
}
})
&#13;
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<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>
&#13;