得到TypeError:运行一些js代码

时间:2013-06-29 03:11:55

标签: javascript

<HTML>
<HEAD>
<TITLE>Mouse Capture</TITLE>
<SCRIPT>
// Get the element, add a click listener...
document.getElementById("parent-list").addEventListener("click",function(e) {
    // e.target is the clicked element!
    // If it was a list item
    if(e.target && e.target.nodeName == "LI") {
        // List item found!  Output the ID!
        console.log("List item ",e.target.id.replace("post-")," was clicked!");
    }
});
</SCRIPT>
</HEAD>
<BODY>
<ul id="parent-list">
    <li id="post-1">Item 1</li>
    <li id="post-2">Item 2</li>
    <li id="post-3">Item 3</li>
    <li id="post-4">Item 4</li>
    <li id="post-5">Item 5</li>
    <li id="post-6">Item 6</li>
</ul>
</BODY>
</HTML>

以上代码来自:http://davidwalsh.name/event-delegate

问题:

我在Chrome和Firework中尝试了以上代码,两者都没有用,在firefox-&gt;控制台中,它显示:TypeError: document.getElementById(...) is null,那么问题是什么?

2 个答案:

答案 0 :(得分:1)

这是因为执行脚本时会加载dom元素。将脚本移动到页面底部以解决问题或在文档就绪

上执行脚本

例如:

<HTML>
<HEAD>
<TITLE>Mouse Capture</TITLE>
<SCRIPT>
window.onload = function(){
    // Get the element, add a click listener...
    document.getElementById("parent-list").addEventListener("click",function(e) {
        // e.target is the clicked element!
        // If it was a list item
        if(e.target && e.target.nodeName == "LI") {
            // List item found!  Output the ID!
            console.log("List item ",e.target.id.replace("post-")," was clicked!");
        }
    });
}
</SCRIPT>
</HEAD>
<BODY>
<ul id="parent-list">
    <li id="post-1">Item 1</li>
    <li id="post-2">Item 2</li>
    <li id="post-3">Item 3</li>
    <li id="post-4">Item 4</li>
    <li id="post-5">Item 5</li>
    <li id="post-6">Item 6</li>
</ul>
</BODY>
</HTML>

答案 1 :(得分:1)

document.getElementById("parent-list")执行时,没有元素具有id parent-list,因为它在elment变为可用之前执行。你可以通过移动你的js代码解决它:

<HTML>
<HEAD>
<TITLE>Mouse Capture</TITLE>
</HEAD>
<BODY>
<ul id="parent-list">
    <li id="post-1">Item 1</li>
    <li id="post-2">Item 2</li>
    <li id="post-3">Item 3</li>
    <li id="post-4">Item 4</li>
    <li id="post-5">Item 5</li>
    <li id="post-6">Item 6</li>
</ul>
<SCRIPT>
// Get the element, add a click listener...
document.getElementById("parent-list").addEventListener("click",function(e) {
    // e.target is the clicked element!
    // If it was a list item
    if(e.target && e.target.nodeName == "LI") {
        // List item found!  Output the ID!
        console.log("List item ",e.target.id.replace("post-")," was clicked!");
    }
});
</SCRIPT>
</BODY>
</HTML>