Javascript/JQuery 忽略更改事件的 stopPropagation

标签 javascript jquery html events

我有一个下拉菜单,其中包含用于搜索的输入字段和带有复选框的标签列表。我添加了 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
});

Here is jfiddle.

关于Javascript/JQuery 忽略更改事件的 stopPropagation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45096788/

相关文章:

html - Ionic ionic 重新排序按钮中断设计

html - 更改图像上的 CSS 高度不起作用?

javascript - Slick Carousel 无法调用方法

javascript - 为什么没有<<<?

JavaScript 静态成员

javascript - 自动展开响应式数据表的子行

javascript - 如何使用 jquery 对事件中的元素进行排序

jQuery 验证添加新方法

html - 为什么这个 IndexedDB put 命令失败了?错误 : DataError: DOM IDBDatabase Exception 0

javascript - requestAnimationFrame 、 readpixel 和隐式清除