嵌套的jQuery onClick事件处理程序多次触发 [英] Nested jQuery onClick event handler fires multiple times

查看:336
本文介绍了嵌套的jQuery onClick事件处理程序多次触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用bootstrap模式,我想为这个模态中的模态和后面的提交按钮注册事件处理程序。

Using a bootstrap modal, i want to register an event-handler both for the modal and the following submit-button inside this modal.

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

Invoking the modal and closing ist subsequently leads to multiple execution of the #modalSubmitButton event. Could you think of any solution to prevent that behaviour and only fire on the actual event, ignoring previous invocations of the modal ? Is my approach of nesting the handlers maybe wrong ?

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

I already tried all combinations of event.stopPropagation / event.unbind(), etc.

$(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()
    });
});


推荐答案

简单修复:不嵌套事件处理程序。通过委派事件处理程序(您已经使用)的实现,不需要。

Simple fix: don't nest event handlers. With the implementation of delegated event handlers (which you're already using) there is no need to.

$(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 onClick事件处理程序多次触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆