首页 > 解决方案 > 事件监听器应用于页面上的几个 divs 元素

问题描述

单击 div 元素时,我正在使用 javascript 显示模式弹出窗口。这对第一个 div 元素(id“myCheck”)非常有用,但我想扩展它以在单击具有相似 id(myCheck2、myCheck3 等)的其他 div 元素时显示模式弹出窗口。

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

  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;
  }

标签: javascripthtmlcss

解决方案


您可以利用事件委托(基本上您在公共父级中附加单击事件侦听器)

<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);
}

推荐阅读