2013-03-22 79 views
4

我无法通过javascript添加eventListener。好的,我有一个创建4个锚元素的函数。我想添加一个事件给他们onmouseover,它调用一个函数来改变他们的背景颜色。下面的代码(看旁边createAnchor的最后一行()来找到相关的代码行。使用Javascript添加事件侦听器DOM

function createAanchor(index) { 
      var a = document.createElement("a"); 
      var text = getText(index); 
      var a = document.createElement("a"); 
      var t = document.createTextNode(text); 
      a.href = getHref(index); 
      a.appendChild(t); 
      a.style.textAlign = "center"; 
      a.style.fontSize = "1.2em"; 
      a.style.color = "white"; 
      a.style.fontFamily = "arial"; 
      a.style.fontWeight = "bold"; 
      a.style.textDecoration = "none"; 
      a.style.lineHeight = "238px"; 
      a.style.width = "238px"; 
      a.style.margin = "5px"; 
      a.style.background = eightColors(index); 
      a.style.position = "absolute"; 
      a.addEventListener("onmouseover", changeColor()); 
      return a; 
    } 

    function changeColor() { 
     alert("EVENT WORKING"); 
    } 

确定这里就是问题所在。当函数到达a.addEventListener("onmouseover", changeColor());function changeColors()执行,但它并不以后执行在onmouseover这是为什么?

+0

P.S.我也尝试了'a.onmouseover = changeColor();'它给出了与'a.addEventListener(“onmouseover”,changeColor())相同的结果;' – Chakotay 2013-03-22 22:43:54

回答

6
  1. 有没有这样的事件onmouseover,该事件被称为mouseover
  2. 您必须将函数引用传递给addEventlistener。正如你已经注意到的那样,()调用函数,所以...不要调用它。

这是应该的:

a.addEventListener("mouseover", changeColor); 

我建议阅读quirksmode.org the excellent articles about event handling

+0

谢谢你提供一个翔实的答案。虽然我有两个问题。 1.'mouseover'和'onmouseover'有什么区别? 2.函数引用是否仅提及函数的名称,但没有参数的括号? – Chakotay 2013-03-22 22:52:36

+0

1:事件名称始终没有“开”。 DOM元素和HTML元素在上具有属性/属性,用于分配一些应该在事件发生时执行的代码。 2:是的,一个函数就像任何其他的值(字符串,数组,布尔)。在'var foo =“bar”;'中,'foo'引用一个字符串。在'function foo(){}'或'var foo = function(){};'中,''foo'引用一个函数。 'foo()'会调用该函数。 – 2013-03-22 22:59:13

+0

再次感谢您提供丰富的答案。我认为这是一个教育帖子,我接受了你的答案,那么你会为我和其他需要关于此问题的信息的用户提出我的问题?也感谢这篇文章,我会确保阅读它! – Chakotay 2013-03-22 23:13:11

4

这是因为你写changeColors(),而不是仅仅changeColors()告诉JavaScript来调用该函数。

换句话说,changeColors本身是一个参考该功能,而changeColors()是指功能,然后将其称为。函数调用的结果(函数的返回值)最终传递给addEventListener()

+0

好的答案谢谢;-) – Chakotay 2013-03-22 23:54:48

-1

我也需要做这样的事情。我在地图上有一个infoWindow,我需要处理该infoWindow中段落的点击事件。所以我这样做:

google.maps.event.addListener(infoWindow, 'domready', function() 
    { 
     paragraph = document.getElementById("idOfThatParagraph"); 
     paragraph.addEventListener("click", function() 
     { 
      //actions that I need to do 
     }); 
    }); 

它适合我。所以我希望它能帮助别人:)

0

好吧我认为我们需要了解何时使用前缀“on”与事件类型。在IE 8或更少的IE8中,我们使用attachEvent和detachEvent,它们相当于addEventListener和removeEventListener。这个问题并不需要一些差异。

使用attachEvent时,事件类型的前缀为“on”,但在addEventListener中不使用前缀。

因此,

elem.attachEvent("onclick",listener); // <= IE8 

    elem.addEventListener("click",listener,[,useCapture]); // other browsers