javascript - 事件监听器应用于页面上的几个 divs 元素
问题描述
单击 div 元素时,我正在使用 javascript 显示模式弹出窗口。这对第一个 div 元素(id“myCheck”)非常有用,但我想扩展它以在单击具有相似 id(myCheck2、myCheck3 等)的其他 div 元素时显示模式弹出窗口。
我尝试了一些事情,例如:
- document.querySelectorAll()
- 在循环中添加点击事件监听器
非常感谢
<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);
}
推荐阅读
- python - 小部件之间的 Tkinter 空间不断增长
- c++ - 如何在 Sublime Text 上为 C++20 构建系统?
- python - 如何在不使用 eval() 和 exec() 在 python 中将列表格式的字符串转换为实际的 python 列表
- python - “NoneType”对象没有属性“display_name”
- git - 如何在正确的分支中转移提交?我将它推入了主分支而不是正确的功能分支
- php - PHP selectfield 从数据库中获取值,更改和 POST
- android - 应用地图路线链接在 chrome 中导航,但不在谷歌地图应用中导航
- java - Open API Maven Plugin:如何为文件上传生成代码
- python - 如何只取熊猫数据框列表的索引 0 并创建一个新的数据框?
- java - 验证 @NotBlank 不适用于 @JsonProperty