addEventListener仅适用于最后一个对象 [英] addEventListener only works on last object

查看:78
本文介绍了addEventListener仅适用于最后一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中,似乎只收到添加了最后一个框(b1)的 otherboxclick调用。如果我更改了添加框的顺序,那么它始终只是最后一个起作用的框。

In the following code, it seems I only get the 'otherboxclick' call for the last box added (b1). If I change the order the boxes are added, it's always just the last one that works.

如何使它适用于所有框?

How can I get it to work for all the boxes?

<html>
<head>
</head>
<body>

<script type="text/javascript">
    function otherboxclick(e){
        alert("other clicked");
    }

    function color_toggle_box(boxid, color, width, height, xpos, ypos)
    {
        this.boxid = boxid;

        document.body.innerHTML += 
            "<div id='" + boxid + "'; '; style='position:absolute;left:" + xpos + "px;top:" + 
            ypos +"px;width:" + width + "px;height:" + height + 
            "px;background:#000'></div>";


        this.boxdiv = document.getElementById(boxid);
        this.boxdiv.style.background = color;
        this.boxdiv.addEventListener('click', otherboxclick, true);
    }

    var b2 = new color_toggle_box("223", "#ff0", 100, 100, 205, 100);
    alert("b2 = " + b2.boxid);
    var b3 = new color_toggle_box("323", "#0ff", 100, 100, 100, 205);
    alert("b3 = " + b3.boxid);
    var b1 = new color_toggle_box("123", "#0f0", 100, 100, 100, 100);
    alert("b1 = " + b1.boxid);
</script>

</body>
</html>


推荐答案

解释为何Lior的代码有效而您的代码却无效:

To explain why Lior's code works and yours doesn't:

document.body.innerHTML +=

总是一个错误。它将文档对象转换为HTML字符串,在该字符串中添加一些文本,然后重新解析整个HTML,以创建新的文档对象来替换所有旧的文档对象。

is always a mistake. It turns your document objects into an HTML string, adds some text to that string, then re-parses the whole HTML back in to make new document objects that replace all the old ones.

在最佳情况下,这可以工作,但速度稍慢。但是,更糟糕的是,所有未序列化为HTML的信息都将完全丢失。其中包括表单字段值,JavaScript属性和引用以及事件侦听器。因此,每次构造color_toggle_box时,您都将销毁先前具有侦听器的所有对象。因此听众将永远不会被呼叫。

In the best case, this will work but is just a bit slow. However a worse side-effect is that any information that doesn't serialise to HTML will be completely lost. That includes form field values, JavaScript properties and references, and event listeners. So, every time you construct a color_toggle_box, you are destroying all the objects you previously had listeners on; hence the listeners will never be called.

这篇关于addEventListener仅适用于最后一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆