我有一个下拉菜单,其中包含用于搜索的输入字段和带有复选框的标签列表。我添加了 stopPropagation 调用,因此每次单击复选框时它都不会关闭,但输入字段上的更改事件因此停止工作。实际上它有效,但我必须用鼠标单击下拉菜单才能激活它。
这是我的 HTML:
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"></button>
<ul class="dropdown-menu scrollable-menu" role="menu">
<li><input class="form-control input-sm" id="search" type="text" style="height:100%; width:100%" /></li>
<li><label class="lbl"><input class="checkbox" type="checkbox" value="1">Something</label></li>
<li><label class="lbl"><input class="checkbox" type="checkbox" value="2">Something else</label></li>
<li><label class="lbl"><input class="checkbox" type="checkbox" value="2">And so on</label></li>
</ul>
</div>
这是我正在使用的功能:
$('.dropdown-menu').click(function (e) {
e.stopPropagation();
});
$("#search").change(function () {
//do stuff
})
最佳答案
当输入失去焦点时,会触发 jQuery change()。
这里是documentation.的链接
The change event is sent to an element when its value changes. This event is limited to elements, boxes and elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.
改用输入,因此每次输入更改时都会触发。
$('.dropdown-menu').click(function (e) {
e.stopPropagation();
});
$("#search").on('input', function () {
// ... do stuff
});
关于Javascript/JQuery 忽略更改事件的 stopPropagation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45096788/