事件侦听器应用于页面上的多个 divs 元素



我正在使用javascript在单击div元素时显示模态弹出窗口。 这适用于第一个div 元素(id "myCheck"(,但我想扩展它以在单击具有类似 id 的其他div 元素(myCheck2、myCheck3 等(时显示模态弹出窗口。

我尝试了一些事情,例如:

  1. document.querySelectorAll((
  2. 在循环中添加点击事件侦听器

非常感谢

<div id="myCheck" name="myCheckName" class="board_order">Some text</div>
<div id="myCheck2" name="myCheckName" class="board_order">Some text</div>
var id = document.getElementById("myCheck");
id.addEventListener("click", displayModal);
function displayModal() {
modal.style.display = "block";
}

一些 CSS

/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 150px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 75%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 60px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}

你可以利用事件委托(基本上你把点击事件侦听器附加到公共父级中(

<div class="parent">
<div data-value="1">div 1</div>
<div data-value="2">div 2</div>
</div>
document.querySelector('.parent').addEventListener('click', handleAction);
function handleAction(ev) {
console.log(ev.target.dataset.value);
}

最新更新