javascript addEventListener 在 Chrome 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15968224/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:45:48  来源:igfitidea点击:

addEventListener not working in Chrome

javascriptgoogle-chromedomjavascript-events

提问by Jose Carrillo

I am following a tutorial on Lynda.com about the new DOM event model.

我正在关注 Lynda.com 上有关新 DOM 事件模型的教程。

This is the code I am working with.

这是我正在使用的代码。

function addEventHandler(oNode, sEvt, fFunc, bCapture){

if (typeof (window.event) != "undefined")
    oNode.attachEvent("on" + sEvt, fFunc);
else
    oNode.addEventListener(sEvt, fFunc, bCapture);
}

function onLinkClicked(e){
alert('You clicked the link');
}

function setUpClickHandler(){
addEventHandler(document.getElementById("clickLink"), "click", onLinkClicked, false);
}


addEventHandler(window, "load", setUpClickHandler, false);

I am adding it to the click event on this link

我将它添加到此链接上的点击事件

<a href="#" title="click me" id="clickLink">Click Me!</a>

It works perfectly fine in IE, Firefox, Opra but not in Chrome. I've looked around, but have not been able to find anything specific yet. Some similar questions but it does not answer my question.

它在 IE、Firefox、Opra 中运行良好,但在 Chrome 中运行不正常。我环顾四周,但还没有找到任何具体的东西。一些类似的问题,但它没有回答我的问题。

I get the following error from the Chrome console

我从 Chrome 控制台收到以下错误

Uncaught TypeError: Object [object HTMLAnchorElement] has no method 'attachEvent' 

any sugestions or a link to the answer.

任何建议或答案的链接。

thanks in advance.

提前致谢。

采纳答案by nnnnnn

Why are you testing:

你为什么要测试:

if (typeof (window.event) != "undefined")

...in order to decide whether to use attachEvent()? Chrome does define window.event, so then your code tries to use attachEvent()which is not defined.

...为了决定是否使用attachEvent()?Chrome 确实定义了window.event,因此您的代码会尝试使用attachEvent()未定义的。

Try instead testing for the method directly:

尝试直接测试该方法:

if (oNode.attachEvent)
    oNode.attachEvent("on" + sEvt, fFunc);
else
    oNode.addEventListener(sEvt, fFunc, bCapture);