试图理解javascript事件处理程序背后的概念

时间:2013-07-17 22:38:03

标签: javascript javascript-events

作为javascript的初学者,人们与

略有混淆
addEventListener()

功能,与使用

相反
variable.onclick

以下是我用

测试它的代码
    /*
     * A simple function to swap the text of two elements        
     */
     function swapFunction(){
        var siteTitle   = document.getElementById("site_title");
        var siteText    = document.getElementById("site_text");

        var temp            = siteTitle.innerHTML;
        siteTitle.innerHTML = siteText.innerHTML;           
        siteText.innerHTML  = temp;
        return false;
     } 

     /*
      * A function to handle the page load
      */
     function fullyLoaded(){            
        var testEvent =       document.getElementById("test_click");            

        /* 
         * Why does the line that has been commented out not work
         * Yet the line beneath it does?
         */

        //testEvent.addEventListener("click", swapFunction(), false);
        testEvent.onclick = swapFunction;
    }

    window.onload = fullyLoaded;        

HTML

<html>
<head>
<title>This is a test application</title>
</head>
<body>
<h1 id="site_title">Welcome To My Site</h1>
<p id="site_text">This is a test site that I am practicing on</p>
<a id="test_click" href="#">test click</a>
</body>
</html>

请帮助解释IE中事件处理程序和addEventListener()或attachEvent()的概念

提前致谢

2 个答案:

答案 0 :(得分:4)

更改

testEvent.addEventListener("click", swapFunction(), false);

testEvent.addEventListener("click", swapFunction, false);

因为当您在函数名后面写braces()时,它会立即执行,但您想将该函数作为参数传递。使用大括号时,不传递函数,传递其返回值。

祝JS学习好运!

答案 1 :(得分:1)

onclick方法基于旧的API,后者被DOM 2 Events取代。在总是优秀的MDN上提到here

  

addEventListener()是随DOM 2 Events规范引入的。在此之前,事件监听器的注册如下:

// Pass a function reference — do not add '()' after it, which would call the function!
el.onclick = modifyText;

下面的注释行不起作用,因为您正在立即调用swapFunction(即,您正在发送swapFunction结果,而不是函数本身)。这是正确的语法:

testEvent.addEventListener("click", swapFunction, false);  

//“swapFunction”,而非“swapFunction()”