【问题标题】:Multiple modals with same script具有相同脚本的多个模式
【发布时间】:2018-10-30 12:03:05
【问题描述】:

我有以下代码来处理页面上的模式打开和关闭。我希望能够在同一页面上加载第二个模式。它将具有相同的类“.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');
  }

【问题讨论】:

  • document.getElementsByClassName("custom-close")[0] 这只是一个 x 按钮。您应该将 onclick 事件处理程序添加到所有这些

标签: javascript html


【解决方案1】:

你的问题是这样的:

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

【讨论】:

  • 完美。谢谢你:)
【解决方案2】:

document.getElementsByClassName("custom-close")[0] 只有一个 x 按钮。您应该将 onclick 事件处理程序添加到所有这些

类似这样的:

 var spans = document.getElementsByClassName("custom-close");
 [].forEach.call(spans, function(el) {
     el.onclick = function() {
       modal.classList.remove('-show');
       body.classList.remove('noscroll');
     }
  })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    相关资源
    最近更新 更多