无法在创建img元素之前将eventListener添加到img元素中

时间:2018-11-28 08:06:14

标签: javascript

我有一个空白页,如果您在任何地方dblclick出现,图像都会在发生dblclick事件的位置消失。效果很好。

我出现了一个函数,根据传入的参数,可以调用该函数淡入元素或淡出。我从getItOut函数调用它,将eventTarget作为第一个参数传递。

但是,现在,我想要一个功能来删除单击时的图像(我们的其他事件并不重要)。

我尝试:

var allImages = []; // initializing array to iterate over img node list
var displayedImages = document.getElementsByTagName('IMG'); get img node list
allImages.push(displayedImages); // push the displayed imgs to the array

// here I want to run this function by iterating with forEach over the array
allImages.forEach(function(el) {el.addEventListener('click', getItOut)}); // getting type error, el.addEventListener is not a function


function getItOut(event){ // this should be called during the above forEach iteration
var getOut = event.target;
appear(getOut, 100, -5, 40);

}

这是codepen链接:

https://codepen.io/damPop/pen/RqMxex

我已注释掉上面的内容,因为抛出的错误不会让任何内容运行。

我在这里做错了什么?我应该检查DOM中是否存在img元素吗?

2 个答案:

答案 0 :(得分:2)

好,是的!

您无法将侦听器连接到不存在的内容。

有两种解决方法。

  1. 等待要创建的元素(document.ready)
  2. 将您的侦听器连接到文档,然后解析以查看单击了什么。 jQuery让您了解:$(document).on('EVENT', 'SELECTOR', function(){})

答案 1 :(得分:1)

因为您将图像作为HTMLCollection而不是DOM元素推送到allImages,并且当您遍历时不能将EventListener绑定到Collection。

allImages.push(displayedImages); //结果为[HTMLCollection(1)]

还要等待图像或DOM内容加载,然后添加eventlistener

它有效。I created a jsfiddle test it in jsfiddle

代码段:

var images = ['//unsplash.it/500/500', '//unsplash.it/400/500','//unsplash.it/500/300'];


function getItOut(event){
 var getOut = event.target;
 appear(getOut, 100, -5, 40);
 //Fixing bug for click same position of disappeared image
 // to not appear again 
 // and fix fadeOut opacity
 var timerId = setInterval(function () {
     const opacity = Number(getOut.style.opacity);
		 if(opacity == 0) {
		 getOut.parentNode.removeChild(getOut);
		 	clearInterval(timerId);
		 }
}, 40)
 
}


document.addEventListener('dblclick', function(event) {
  var currentImg;
  var ix = event.clientX;     // Get the coordinates
var iy = event.clientY; 
var x = document.createElement("IMG");
    x.setAttribute("src", images[0]);
    x.setAttribute("width", "304");
    x.setAttribute("height", "228");
    x.style.position="absolute";
   x.style.top= iy + 'px';
  x.style.left= ix + 'px';
  x.style.opacity = 0.1;
    document.body.appendChild(x);
	x.addEventListener('click', getItOut)
  //x.classList.add("fadeIn");
  var ix = "";
  var iy = "";
  console.log(event.currentTarget);
  appear(x, 0, 5, 40);
  

});



function appear(elm, i, step, speed){
    var t_o;
    //initial opacity
    i = i || 0;
    //opacity increment
    step = step || 5;
    //time between opacity increments in ms
    speed = speed || 50; 

    t_o = setInterval(function(){
        //get opacity in decimals
        var opacity = i / 100;
        //set the next opacity step
        i = i + step; 
        if(opacity > 1 || opacity < 0){
            clearInterval(t_o);
            //if 1-opaque or 0-transparent, stop
            return; 
        }
        //real browsers
        elm.style.opacity = opacity;
        //IE
        elm.style.filter = 'alpha(opacity=' + opacity*100 + ')';
				
    }, speed);
}

相关问题