-2
<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->console 中,它显示:TypeError: document.getElementById(...) is null,那么问题是什么?

4

2 回答 2

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>
于 2013-06-29T03:14:31.807 回答
1

执行时document.getElementById("parent-list")没有 id 为 parent-list 的元素,因为它在元素可用之前执行。你可以通过移动你的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>
于 2013-06-29T03:15:14.203 回答