【问题标题】:Nested jQuery onClick event handler fires multiple times嵌套的 jQuery onClick 事件处理程序触发多次
【发布时间】:2015-05-13 19:10:02
【问题描述】:

使用引导模式,我想为模式和此模式内的以下提交按钮注册一个事件处理程序。

随后调用 modal 并关闭 ist 会导致多次执行 #modalSubmitButton 事件。你能想出任何解决方案来防止这种行为并且只在实际事件上触发,而忽略之前对 modal 的调用吗?我嵌套处理程序的方法可能是错误的吗?

我已经尝试过event.stopPropagation/event.unbind()等的所有组合。

$(document).on('click', '#myModalID' function () {

    // i fetch some data from the clicked element here
    //  and make it accessible to the subsequent eventHandler

        $(document).on('click', '#modalSubmitButton' function () {

            // eventually calling service on click of button
            invokeService()
    });
});

【问题讨论】:

    标签: jquery twitter-bootstrap modal-dialog nested propagation


    【解决方案1】:

    简单修复:不要嵌套事件处理程序。有了委托事件处理程序(您已经在使用)的实现,就没有必要了。

    $(document).on('click', '#myModalID' function () {
        // i fetch some data from the clicked element here
        //  and make it accessible to the subsequent eventHandler
    });
    
    $(document).on('click', '#modalSubmitButton' function () {
        // eventually calling service on click of button
        invokeService()
    });
    

    【讨论】:

    • 您好,Rory,感谢您的快速回复。我想将一些数据作为参数传递给下一个处理程序。我没有找到解决方案如何在不实际调用它的情况下从函数/事件处理程序 A --> B 传递参数。有什么想法吗?
    • 您实际上不能在事件处理程序之间传递参数。您可以在两个处理程序的范围内使用变量,或者在可以从两者读取的元素上设置data 属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多