JavaScript事件处理代码多次被调用 [英] JavaScript event handling code get's called multiple times

查看:83
本文介绍了JavaScript事件处理代码多次被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要你的帮助.我目前正在使用JavaScript中的模式库来为我的客户显示模式:

I need your help. I'm currently working with a modal lib in JavaScript to display a modal for my customers:

https://github.com/vodkabears/Remodal/tree/1.1.1

不幸的是,如果用户单击某个按钮,我的事件处理将无法正常工作.浏览手册时,您可以在 Events 下面看到以下事件处理程序:

Unfortunately my event handling in case the user clicks a button don't works like expected. When you take a look into the manual, you can see under the point Events the following event handler:

$(document).on('cancellation', '.remodal', function () {
  console.log('Cancel button is clicked');
});

例如,当按下取消"按钮时,将触发该按钮.因为我将一个弹出窗口用于多种操作,所以我需要将事件处理程序直接附加到该调用.所以首先我写了一个打开弹出窗口的函数:

This one get's triggered for example when the cancel button get's pressed. Because I'm using one popup for multiple things, I need to attach the event handler to the call directly. So first I've wrote a function that opens the popup:

function openRemodal( remodalId ) {
    let remodal = $( `[data-remodal-id=${remodalId}]` );

    remodal.remodal().open();

    return remodal; // <- added to handle events
}

我可以这样调用该函数:

I can call this function that way:

openRemodal( 'information-remodal' ); 

要完成事件处理,我现在在函数中返回了重新模式并重新编写了呼叫:

To get an event handling done, I've now returned the remodal in the function and re-wrote my call:

openRemodal( 'information-remodal' ).on( 'cancellation', function () {
    alert( 'Test' );
} );

这似乎可行,但是以某种方式,当我重复打开弹出窗口并按下按钮时,任何新的打开都会多次显示警报.

This seems to work but somehow when I repeat the opening of the popup and pressing the button, the alert get's shown multiple times increased by any new opening.

我不确定为什么会这样,为什么.您能帮我解决这个问题吗?我只想在其中一次调用任何函数.

I'm not sure why this happens and why. Can you please help me get this working? I just want to call any function in there once - any time.

推荐答案

JQuery具有 .one 方法,请尝试使用该方法代替 .on .回调应该只运行一次. https://api.jquery.com/one/

JQuery has a .one method ... try using that in place of .on. The callback should run only once. https://api.jquery.com/one/

这篇关于JavaScript事件处理代码多次被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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