如何将eventListener添加到将更改另一个元素显示的htmlCollection



目标:点击框(x(,弹出窗口(x(;

这是我的第一个javascript项目,我已经做了大量的研究,但我仍然在挣扎。我之所以使用getElementByClassList,是因为它返回一个数组。然后,我会获取数组并获得相应的弹出框,并更改其在css中的显示设置。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="box1 boxes"></div>
<div>
<div class="box2 boxes"></div>
<div class="box3 boxes"></div>
</div>
<div class="popup1"></div>
<div class="popup2"></div>
<div class="popup3"></div>

<script>
const boxes = document.getElementsByClassName('boxes');
// i would like to add an eventlistener for each object in the array
//
</script>
</body>
</html>

document.addEventListener("DOMContentLoaded", () => { // wait till all the DOM is Loaded, since querying objects at this point they are not there yet.
const boxes = document.querySelectorAll(".boxes"); // or use getElementsBy...

boxes.forEach(box => { // we are adding a click event listener to each box
box.addEventListener('click', (e) => {
const boxNumber = e.target.className.match(/box(d)/)[1]; // through a regex we get the box number of the className
const popup = document.querySelector(`.popup${boxNumber}`);

console.log(popup)
// do whatever you want with the popup, add a className or whatever to open it :)
});
});
});
.boxes {
height: 20px;
width: 50px;
background: red;
margin: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="box1 boxes"></div>
<div>
<div class="box2 boxes"></div>
<div class="box3 boxes"></div>
</div>
<div class="popup1"></div>
<div class="popup2"></div>
<div class="popup3"></div>

<script>
const boxes = document.getElementsByClassName('boxes');
// i would like to add an eventlistener for each object in the array
//
</script>
</body>
</html>

方法getElementsByClassName((指示返回一个html对象数组,以防存在具有传递css类的元素。

您必须通过数组对象进行迭代的第一步:

for (int index = 0; index < boxes.length; index++)
{
}

在内循环访问每个元素并分配事件句柄

boxes[index].addEventListnener('click', function()
{
});

在声明的匿名函数的主体中添加您的代码。

您可以尝试:

const boxes = document.getElementsByClassName('boxes');
const popups = document.querySelectorAll(".popups");
boxes.forEach((box,index)=>box.addEventListener("click",()=>{
const popup = popups[index]; // This gets the popup based on the box index so you will have to setup the html so that the popup for box1 is the first then popup for box2 second etc.

// Add styles to popup to display it
// Example
popup.style.opacity = "1";

})

访问"mdn文档"或"youtube",了解forEach等数组方法如何工作

相关内容

最新更新