2013-05-12 59 views
0

这段代码有什么问题?我在IE10和Firefox中测试了它,但没有提出click事件。为什么点击事件没有提出?

<html> 
    <head> 
    <title>Sandbox</title> 
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> 

    <style type="text/css" media="screen"> 
    #t1, #t2 { border: 2px solid gray; } 
    #t2 { background-color: pink; } 
    </style> 

    <script> 
    // Function to change the content of t2 
    function modifyText(new_text) { 
    var t2 = document.getElementById("t2"); 
    t2.firstChild.nodeValue = new_text;  
    } 

    // Function to add event listener to table 
    var el = document.getElementById("outside"); 
    el.addEventListener("click", function(){modifyText("four")}, false); 
    </script> 

    </head> 

    <body> 
    <table id="outside"> 
     <tr><td id="t1">one</td></tr> 
     <tr><td id="t2">two</td></tr> 
    </table> 
    </body> 
    </html> 

回答

3

JavaScript是DOM的运行前准备:

Uncaught TypeError: Cannot call method 'addEventListener' of null 

不能可靠地与DOM交互它准备好之前,所以将你的JavaScript以身体的底部。

万一你正在考虑使用window.load = function() {...}的,附着于window.load回调将不会运行,直到资源的所有加载,这可能不是你想要的。有没有简单的纯JavaScript的替代jQuery的$(document).ready(),但你可以使用从这里的东西:$(document).ready equivalent without jQuery

1

使用

window.onload = function() { 
    var el = document.getElementById("outside"); 
    el.addEventListener("click", function(){modifyText("four")}, false); 
} 
相关问题