addEventListener not working in Chrome

懵懂的女人 提交于 2019-12-23 08:57:07

问题


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

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.

I get the following error from the Chrome console

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

any sugestions or a link to the answer.

thanks in advance.


回答1:


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.

Try instead testing for the method directly:

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


来源:https://stackoverflow.com/questions/15968224/addeventlistener-not-working-in-chrome

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