javascript - 具有相同脚本的多个模式

标签 javascript html

我有以下代码来处理页面上的模式打开和关闭。我希望能够在同一页面上加载第二个模式。它将具有相同的类“.custom-modal”,但具有不同的 ID。

使用我当前的代码,两个模式都会打开,但只有第一个模式可以关闭。

var modal;
  // Get the button that opens the modal
  var btns = document.querySelectorAll(".customModalTrigger");
  // Get the <span> element that closes the modal
  var span = document.getElementsByClassName("custom-close")[0];
  var body = document.body;

  // When the user clicks the button, open the modal
  [].forEach.call(btns, function(el) {
    el.onclick = function() {
      // Get the modal
      modal = document.querySelector('#' + el.id + '.custom-modal');
      modal.classList.add('-show');
      body.classList.add('noscroll');
    }
  })

  // When the user clicks on <span> (x), close the modal
  span.onclick = function() {
      modal.classList.remove('-show');
      body.classList.remove('noscroll');
  }

最佳答案

您的问题是这样的:

var span = document.getElementsByClassName("custom-close")[0];

具体来说,[0]。您仅将事件监听器应用于第一个匹配元素,而不是其他元素。相反,请尝试:

var span = document.getElementsByClassName("custom-close");
for (var i = 0; i < span.length; i++){
    span[i].onclick = = function() {
        modal.classList.remove('-show');
        body.classList.remove('noscroll');
    }
}

关于javascript - 具有相同脚本的多个模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53057174/

相关文章:

javascript - 在不止一次添加允许的文件总数时,在更改事件监听器中对文件数组进行切片 - JavaScript

javascript - 需要.js : When extending a module can I use prototype directly or I should use extend as well?

javascript - 单击选择,添加选项,然后打开选择下拉列表

java - 使用 JavaScript 提交

javascript - 将纸张图标和文本左对齐?

javascript - 扩展表单的高度以适合表单中的内容

javascript - 如何在提交无效表单后保留到页面(CodeIgniter 3)

javascript - 将 "x"参数数量设置为函数属性

Javascript "Cannot read property ' 未定义的标题'在1个长度项上

html - 垂直对齐div中的图像和文本