事件处理程序中的事件处理程序正在相乘 [英] Event handler inside event handler is multiplying

查看:119
本文介绍了事件处理程序中的事件处理程序正在相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码

jQuery('#parent').on('click', jQuery('#fileInput'), function (e) {
    jQuery(e.target).attr('data-fileurl', '');
    jQuery('#parent').on('change', jQuery('#fileInput'), function (e) {
        usefulFunction(jQuery(e.target);
    }
}

这个想法是要检测文件浏览中是否选择了"cancel",然后成功.

The idea is to detect if cancel was chosen on file browse, and it succeeds at that.

问题是,如果再次单击它,它将运行.on('chance')两次,从而运行usefulFunction.每次单击都会添加一个更改事件处理程序.每次更改jQuery('#fileInput')时,usefulFunction只应运行一次.如何防止这种意外行为?

The problem is if I click it again, then it will run the .on('chance') twice and thus run usefulFunction. Each click adds a change event handler. usefulFunction should only be run once for each time jQuery('#fileInput') is changed. How can I prevent this unexpected behavior?

推荐答案

您应使用 one 方法代替:

You should use one method instead:

jQuery('#parent').one('change', jQuery('#fileInput'), function (e) {
                    ^
...

这篇关于事件处理程序中的事件处理程序正在相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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