0

这是我的代码:

<html>
<head>
    <script type="text/javascript" language="javascript">
        function load() {
            div1 = document.getElementById('div1');
            div2 = document.getElementById('div2');
            function clicky() {
                alert('1');
            }
            div2.addEventListener('click', clicky);
            //div1.innerHTML += 'ooooooofdsfdsfdsfdsfdsfsdfdsfdsfdsfdsklfdsjfkldsjfkldsjfldsjfkldsjfkldsjfdskl';
        }       
    </script>
</head>
<body onload="load();">
    <div id="div1" style="width : 300px; height : 300px; background-color : red; position : absolute">

        <div id="div2" style="width : 20px; height : 20px; background-color : green; position : absolute; right : 5px; top : 5px;">X</div>

    </div>
</body>

所以,我在 div1 中有 div2。如果评论的字符串真的被评论了,一切正常:点击 div2 会引起警报。但是,如果我将 smth 添加到 div1.innerHTML,事件处理程序将不起作用。哪里有问题?

4

1 回答 1

1

你的代码

div1.innerHTML += 'ooooooofdsfdsfdsfdsfdsfsdfdsfdsfdsfdsklfdsjfkldsjfkldsjfldsjfkldsjfkldsjfdskl';

实际上意味着

div1.innerHTML = div1.innerHTML + ooooooofdsfdsfdsfdsfdsfsdfdsfdsfdsfdsklfdsjfkldsjfkldsjfldsjfkldsjfkldsjfdskl';

所以从字面上看,你正在用一个新字符串覆盖 div1 的 innerHTML,这反过来又创建了一个新的 div2 对象。因此,您需要在设置 innerHTML 后添加点击侦听器。

于 2013-04-06T10:14:49.760 回答