使用JS,打开和关闭按钮可以工作,但是escape总是试图关闭最后一个模态

时间:2017-09-07 14:48:22

标签: javascript

我已经使用了我的按钮,但我无法弄清楚如何使用正确的模态使转义键工作。它总是“关闭”最后一个模态,无论我有多少。

这一切都在我的for循环中,所以我不明白为什么thisModal跟踪到正确的按钮,而不是document.onkeydown函数。

另外,没有关于使用jQuery的评论请:)。

const modalToggle = document.querySelectorAll(".button"),
  modal = document.querySelectorAll(".modal"),
  closeButton = document.querySelectorAll(".close");

if (modalToggle) {

  for (i = 0; i < modalToggle.length; i++) {
    let thisToggle = modalToggle[i];
    let thisModal = modal[i];
    let thisClose = closeButton[i];

    thisToggle.addEventListener("click", () => openModal(thisModal));
    thisClose.addEventListener("click", () => closeModal(thisModal));
    document.onkeydown = (e) => {
      if (e.keyCode == 27) {
        console.log(thisModal); // Is always the LAST modal... why?
        closeModal(thisModal);

      }
    }
  };
}

function openModal(el) {
  el.style.display = "block";
}

function closeModal(el) {
  el.style.display = "none";
}
.modal {
  display: none;
  background: lightgray;
  border: 1px solid black;
  width: 50%;
  height: 100px;
}
<button class="button">One</button>
<button class="button">Two</button>
<button class="button">Three</button>

<div class="modal">ONE
  <button class="close">Close</button>
</div>

<div class="modal">TWO
  <button class="close">Close</button>
</div>

<div class="modal">Three
  <button class="close">Close</button>
</div>

1 个答案:

答案 0 :(得分:1)

这是因为for循环的每次运行都覆盖了之前的绑定。试试这个,按esc关闭所有模态

const modalToggle = document.querySelectorAll(".button"),
  modal = document.querySelectorAll(".modal"),
  closeButton = document.querySelectorAll(".close");

if (modalToggle) {

  for (i = 0; i < modalToggle.length; i++) {
    let thisToggle = modalToggle[i];
    let thisModal = modal[i];
    let thisClose = closeButton[i];

    thisToggle.addEventListener("click", () => openModal(thisModal));
    thisClose.addEventListener("click", () => closeModal(thisModal));
  };
  document.onkeydown = (e) => {
      if (e.keyCode == 27) {
          for (i = 0; i < modalToggle.length; i++) {
               let thisToggle = modalToggle[i];
              let thisModal = modal[i];
              let thisClose = closeButton[i];
              console.log(thisModal); // Is always the LAST modal... why?
              closeModal(thisModal);
          };


      }
    }
}

function openModal(el) {
  el.style.display = "block";
}

function closeModal(el) {
  el.style.display = "none";
}
.modal {
  display: none;
  background: lightgray;
  border: 1px solid black;
  width: 50%;
  height: 100px;
}
<button class="button">One</button>
<button class="button">Two</button>
<button class="button">Three</button>

<div class="modal">ONE
  <button class="close">Close</button>
</div>

<div class="modal">TWO
  <button class="close">Close</button>
</div>

<div class="modal">Three
  <button class="close">Close</button>
</div>