简体   繁体   English

如何在函数中使用事件监听器?

[英]How to use eventlisteners in functions?

I need to ask confirmation from the user before unloading the page.在卸载页面之前,我需要询问用户的确认。 If I do this in JS, it works:如果我在 JS 中这样做,它会起作用:

window.onbeforeunload = function () { //close confirm
    return '';
}

but when I place it into a function to make this more flexible, I seems to be not registered:但是当我将它放入 function 以使其更灵活时,我似乎没有注册:

function sth()
{
    window.addEventListener('beforeunload', closeConfirm, false);
}

function closeConfirm()
{
    return '';
}

Can someone please tell me the difference?有人可以告诉我区别吗? Removing is also not working in a function, after event was registered outside the functions in plain JS.在事件在普通 JS 的函数之外注册后,在 function 中删除也不起作用。 sth() is called by pressing a button. sth() 通过按下按钮来调用。 I need to enable this eventlistener on login, and remove on logout or timeout, but I cant make it work with function calls, but just when the page loads.我需要在登录时启用此事件侦听器,并在注销或超时时删除,但我无法使其与 function 调用一起工作,但只是在页面加载时。

---REFRESH--- Example: https://jsfiddle.net/6mvuet1h/1/ ---REFRESH--- 示例: https://jsfiddle.net/6mvuet1h/1/

If you comment out the 2-4 lines, this is not working.如果您注释掉 2-4 行,这是行不通的。

So I'm editing my answer, because I misunderstood your problem before.所以我正在编辑我的答案,因为我之前误解了你的问题。

On beforeundload mdn page we can read that some browsers (chrome included) need event.returnValue to be set.beforeundload mdn 页面上,我们可以看到一些浏览器(包括 chrome)需要设置event.returnValue Some other browsers need event.preventDefault() to be called.其他一些浏览器需要调用event.preventDefault() So your closeConfirm function should look like this:所以你的closeConfirm function 应该是这样的:

function closeConfirm(event)
{
    event.preventDefault();
    event.returnValue = '';
    return '';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM