JavaScript 和订阅事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7062715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript and subscribing to Events
提问by Jonathan
I have something like this in a JavaScript control, how does one subscribe to this event?
我在 JavaScript 控件中有类似的内容,如何订阅此事件?
if(typeof(pnlDialog.onclose) == 'function')
pnlDialog.onclose();
I thought it was something like this, but haven't been successful.
我以为是这样的,但没有成功。
var mycontrol = document.getElementById('myDialog');
mycontrol.attachEvent('onclose', function()
{
alert('closed');
});
回答by Andreas Eriksson
.attachEvent is a microsoft-developed function, I think it pretty much only works in internet explorer.
.attachEvent 是微软开发的函数,我认为它几乎只适用于 Internet Explorer。
Try .addEventListener, with this syntax:
尝试 .addEventListener,使用以下语法:
var mycontrol = document.getElementById('myDialog');
mycontrol.addEventListener('onclose', function()
{
alert('closed');
}, false);
The "false" determines if the function should be executed in the capturing (true) or bubbling (false) phase. False should be fine.
"false" 决定函数应该在捕获 (true) 还是冒泡 (false) 阶段执行。假的应该没问题。
回答by Jamiec
Looks like it's not using events at all, its just using a late bound function. Therefore use this:
看起来它根本不使用事件,它只是使用后期绑定函数。因此使用这个:
var mycontrol = document.getElementById('myDialog');
mycontrol.onclose = function(){
alert("Closed");
}
回答by Jonathan
Okay, I see its really simple
好吧,我看它真的很简单
var mycontrol = document.getElementById('myDialog');
mycontrol.onclose = function()
{
alert('closed');
};