addEventListener在Chrome中不起作用 [英] addEventListener not working in Chrome

查看:1038
本文介绍了addEventListener在Chrome中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



这是我正在使用的代码。

  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('你点击了链接');
}

函数setUpClickHandler(){
addEventHandler(document.getElementById(clickLink),click,onLinkClicked,false);
}


addEventHandler(window,load,setUpClickHandler,false);

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

 < a href =#title =click meid =clickLink>点击我!< / a> 

它在IE,Firefox,Opra中完美无缺,但不在Chrome中。我周围环顾四周,但还没有找到任何具体的东西。一些类似的问题,但它没有回答我的问题。



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

 未捕获TypeError :Object [object HTMLAnchorElement]没有方法'attachEvent'

任何提示或链接到答案。



提前感谢。

解决方案

为什么要测试:

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

...为了决定是否使用 attachEvent()? Chrome确实定义了 window.event ,所以你的代码试图使用没有定义的 attachEvent() p>

尝试直接测试方法:

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


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.

解决方案

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);

这篇关于addEventListener在Chrome中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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