Event handler inside event handler is multiplying

故事扮演 提交于 2019-12-25 08:48:01

问题


I have this code

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

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

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?


回答1:


You should use one method instead:

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


来源:https://stackoverflow.com/questions/38957233/event-handler-inside-event-handler-is-multiplying

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!