我有3张html格式的图片.
我 Select 包含querySelectorAll
的图像,将它们转换为数组,然后:
Step1
我将它们包含在一个<div>
标记中,添加一个.img-container
类,使用outerHTML
.
Step2
我向图像中添加了一个事件侦听器.
当图片被点击时,我会在控制台记录"img已被点击".
如果我单独运行Step1,代码可以运行.
如果我单独运行Step2,代码就可以运行.
当我try 同时运行Step1和Step2时,事件侦听器(步骤2)不起作用.
有什么帮助吗?
// Select all img tags
const allImg = document.querySelectorAll('img');
// ***STEP 1 ***
//Enclose imgs in divs (and add img-container class)
const allImgArr = Array.from(allImg).map((curr) =>
curr.outerHTML = '<div class="img-container">' + curr.outerHTML + '</div>' );
// ***STEP 2***
//Click on image to console.log 'img has been clicked'
const allImgArrTwo = Array.from(allImg).map((curr) =>
curr.addEventListener('click', function() {
console.log ('img has been clicked')
}));
.img-container {
display: flex;
align-items: center;
justify-content: center;
background-color: red;
width: 250px;
height: 250px;
}
<p>Img 1</p>
<img src="https://images.pexels.com/photos/574071/pexels-photo-574071.jpeg" width="100" height="100" alt="">
<p>Img 2</p>
<img src="https://images.pexels.com/photos/1181676/pexels-photo-1181676.jpeg" width="100" height="100" alt="">
<p>Img 3</p>
<img src="https://images.pexels.com/photos/1181244/pexels-photo-1181244.jpeg" width="100" height="100" alt="">