Javascript Can';不正确:从getElementsByClassName向元素添加事件侦听器

Javascript Can';不正确:从getElementsByClassName向元素添加事件侦听器,javascript,dom,Javascript,Dom,请告诉我下面的代码有什么问题: for(var i = 0; i < image.length; i++) { image[i].appendChild(overlay); image[i].addEventListener("mouseover", function() { this.firstChild.style.backgroundColor = "rg

请告诉我下面的代码有什么问题:

            for(var i = 0; i < image.length; i++) {
                image[i].appendChild(overlay);

                image[i].addEventListener("mouseover", function() {
                    this.firstChild.style.backgroundColor = "rgba(0, 0, 0, 0)";
                    this.style.backgroundSize = "340px 240px";
                    this.style.WebkitTransition = "all 0.5s";
                    this.style.transition = "all 0.5s";
                }, false);  

                image[i].addEventListener("mouseout",function() {
                    this.firstChild.style.backgroundColor = "rgba(0, 0, 0, 0.7)";
                    this.style.backgroundSize = "300px 200px";
                    this.style.WebkitTransition = "all 0.5s";
                    this.style.transition = "all 0.5s";
                }, false);
            }
我从浏览器控制台得到的错误如下:

如果我遗漏了你需要知道的任何事情,请告诉我。或者,如果您对如何改进此代码有任何建议,请将其付诸实施


注意:没有jQuery。

您只有一个
overlay
元素,您只是在更改它的父元素。在循环之后,它被附加到
图像
集合中的最后一个元素

要解决此问题,您可以在每次将覆盖添加到新的父项时创建覆盖的副本,如下所示:

image[i].appendChild(overlay.cloneNode(true));
var clone = overlay.cloneNode(true);
clone.id = clone.id + i; // Adds i to the end of the id, use date or some else unique string instead, if you're running the loop multiple times
image[i].appendChild(clone);
为了防止克隆的元素有一个
id
,您必须为每个克隆创建一个新的
id
,如下所示:

image[i].appendChild(overlay.cloneNode(true));
var clone = overlay.cloneNode(true);
clone.id = clone.id + i; // Adds i to the end of the id, use date or some else unique string instead, if you're running the loop multiple times
image[i].appendChild(clone);

一个图像怎么可能有第一个子元素呢?
firstChild
可能是一个文本节点吗?它是一个类的名称,而不是一个实际的图像。是的,但是你只有一个元素,你只是在改变它的父元素。在循环之后,它被附加到
image
collection.Yep中的最后一个元素,使用示例方法。如果克隆的元素具有
id
,请确保
id
在克隆后也是唯一的。