为什么我的JS弹出窗口不适用于多个元素?

时间:2019-06-01 09:30:33

标签: javascript html css

我实际上是从头开始创建一个论坛。当我们单击删除时,此脚本会创建一个弹出窗口,我将2个按钮删除,但只有一个工作。 代码:

HTML代码->

<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
    <link rel="stylesheet" type="text/css" href="styletest.css">
  </head>
  <body>
    <a href="#" id="remove_openpopup">remove</a>
    <a href="#" id="remove_openpopup">remove2</a>

    <div id="popup" class="popup">
      <div class="popup_content">
        <span class="close">&times;</span>
        <p>Are you sure you wan't delete this categorie ?</p>
        <button class="button_popup close_button">No</button>
        <button class="button_popup close_button" onclick='document.getElementById("remove").submit()'>Yes</button>
      </div>
    </div>
  </body>
</html>

JS:

var modal = document.getElementById("popup");

var btn = document.getElementById("remove_openpopup");

var span = document.getElementsByClassName("close")[0];
var span2 = document.getElementsByClassName("close_button")[0];

btn.onclick = function() {
  modal.style.display = "block";
}

span.onclick = function() {
  modal.style.display = "none";
}

span2.onclick = function() {
  modal.style.display = "none";
}

window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

我该怎么做:当我单击“删除”时,它会打开我的弹出窗口,但同时也会删除“ remove2”? 你能帮我吗 ? :)

1 个答案:

答案 0 :(得分:1)

只是一个示例:) 在HTML中,我将id="remove_openpopup"更改为class="remove_openpopup"

<a href="#" class="remove_openpopup">remove</a>
<a href="#" class="remove_openpopup">remove2</a>

<script>中,我将执行以下操作。

<script>
var modal = document.getElementById("popup");
var btns = Array.prototype.slice.call(document.querySelectorAll(".remove_openpopup"));
var span = document.getElementsByClassName("close")[0];
var span2 = document.getElementsByClassName("close_button")[0];
btns.forEach(function(btn) {
  btn.onclick = function() {
    modal.style.display = "block";
  }
});
span.onclick = function() {
  modal.style.display = "none";
}
span2.onclick = function() {
  modal.style.display = "none";
}
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
</script>