模态工作,直到重复

时间:2017-07-05 20:21:00

标签: javascript

我有一个我创建的javascript模式,工作正常,除非页面上有2个。当页面中存在2个时,第一个将起作用,但下一个现在可以。

这是控制它的JS:

// Get the button that opens the modal
let trigger = document.getElementsByClassName("js-modal")[0];
trigger.onclick = function() {
  modal.style.display = "block";
};

// Get the modal linked with with trigger element
let modal = document.getElementById(
  trigger.href.substring(trigger.href.indexOf("#") + 1)
);

// When the user clicks the button, open the modal
let allClose = modal.getElementsByClassName("js-modal-close");


// All elments linked to the modal can close the modal
for (let i = 0; i < allClose.length; i++) {
  allClose[i].onclick = function() {
    modal.style.display = "none";
  };
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(e) {
  if (e.target == modal) {
     modal.style.display = "none";
  }
};

这是一个working example。我已经尝试过使用var代替let,但不是100%确定如何将它们范围化为特定的html结构。

4 个答案:

答案 0 :(得分:2)

您需要为每个模态使用唯一ID:

<div id="modal-1" class="m-modal">...</div>
<div id="modal-2" class="m-modal">...</div>

并为每一个设置触发器,而不仅仅是第一个:

let triggers = [].slice.call(document.getElementsByClassName('js-modal'))

triggers.forEach(function(trigger) {
 // ...
}

JSFiddle演示:https://jsfiddle.net/eoy2erpp/1/

答案 1 :(得分:1)

这是一个解决方案,很脏但很有效 jsfiddle

var trigger = document.getElementsByClassName("js-modal")[1];
trigger.onclick = function() {
modal.style.display = "block";
};

答案 2 :(得分:1)

let trigger = document.getElementsByClassName("js-modal")[0];

您只绑定到js中的第一个按钮。没有什么是你的第二个

答案 3 :(得分:1)

更改您的javascript:

    // Get the button that opens the modal
let trigger = document.getElementsByClassName("js-modal")[0];

let trigger1 = document.getElementsByClassName("js-modal")[1];

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

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

// Get the modal linked with with trigger element
let modal = document.getElementById(
  trigger.href.substring(trigger.href.indexOf("#") + 1)
);

// When the user clicks the button, open the modal
let allClose = modal.getElementsByClassName("js-modal-close");


// All elments linked to the modal can close the modal
for (let i = 0; i < allClose.length; i++) {
  allClose[i].onclick = function() {
    modal.style.display = "none";
  };
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(e) {
  if (e.target == modal) {
     modal.style.display = "none";
  }
};