Вызов Div из атрибута ID

1

Мне нужно повторять кнопку несколько раз по всему сайту. Однако я не могу этого сделать из-за атрибута "id". Как я могу вызвать свой javascript, чтобы ответить на "div", а не на "id". Простое размещение <button class="modalbutton"></div> не сработало для меня.

Подхватил этот код от w3schools. Практически новичок и нигде не смог найти ответ на этот вопрос.

    // Get the modal
    var modal = document.getElementById('detailmodal');


    // Get the button that opens the modal
    var btn = document.getElementById("modalbutton");

    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];

    // When the user clicks the button, open the modal 
    btn.onclick = function() {
      modal.style.display = "block";
    }

    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
      modal.style.display = "none";
    }

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
      if (event.target == modal) {
        modal.style.display = "none";
      }
    }
/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
    position: relative;
    float: right;
    background-color: #fefefe;
    margin: auto;
    padding: 0;
    border: 1px solid #888;
    max-width: 850px;
    width: 100%;
    height: 100%;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
    -webkit-animation-name: animatetop;
    -webkit-animation-duration: 0.4s;
    animation-name: animatetop;
    animation-duration: 0.8s
}

/* Add Animation */
@-webkit-keyframes animatetop {
  from {right:-100px; opacity:0} 
  to {right:0; opacity:1}
}

@keyframes animatetop {
  from {right:-100px; opacity:0}
  to {right:0; opacity:1}
}
<button id="modalbutton" class="modalbutton">Open Modal</button>

<button id="modalbutton" class="modalbutton">Open Modal</button>

<button id="modalbutton" class="modalbutton">Open Modal</button>

<!-- The Modal -->
<div id="detailmodal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h2>Modal Header</h2>
    </div>
    <div class="modal-body">
      <p>Some text in the Modal Body</p>
      <p>Some other text...</p>
    </div>
    <div class="modal-footer">
      <h3>Modal Footer</h3>
    </div>
  </div>

</div>
  • 0
    Не используйте одинаковые идентификаторы для нескольких элементов в DOM. Идентификаторы элементов должны быть уникальными.
Теги:

2 ответа

1
Лучший ответ

Пользователь document.querySelectorAll и получить все ваши кнопки через атрибут класса. Затем переберите список кнопок и индивидуально добавьте слушателя на них.

const btns = document.querySelectorAll(".modalbutton");

// When the user clicks the button, open the modal 
btns.forEach(btn=>btn.onclick = function() {
  modal.style.display = "block";
});

Полное решение:

// Get the modal
var modal = document.getElementById('detailmodal');


// Get the button that opens the modal
var btns = document.querySelectorAll(".modalbutton");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 
btns.forEach(btn=>btn.onclick = function() {
  modal.style.display = "block";
});

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
/* The Modal (background) */

.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4);
  /* Black w/ opacity */
}


/* Modal Content */

.modal-content {
  position: relative;
  float: right;
  background-color: #fefefe;
  margin: auto;
  padding: 0;
  border: 1px solid #888;
  max-width: 850px;
  width: 100%;
  height: 100%;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  -webkit-animation-name: animatetop;
  -webkit-animation-duration: 0.4s;
  animation-name: animatetop;
  animation-duration: 0.8s
}


/* Add Animation */

@-webkit-keyframes animatetop {
  from {
    right: -100px;
    opacity: 0
  }
  to {
    right: 0;
    opacity: 1
  }
}

@keyframes animatetop {
  from {
    right: -100px;
    opacity: 0
  }
  to {
    right: 0;
    opacity: 1
  }
}
<button id="modalbutton" class="modalbutton">Open Modal</button>

<button id="modalbutton" class="modalbutton">Open Modal</button>

<button id="modalbutton" class="modalbutton">Open Modal</button>

<!-- The Modal -->
<div id="detailmodal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h2>Modal Header</h2>
    </div>
    <div class="modal-body">
      <p>Some text in the Modal Body</p>
      <p>Some other text...</p>
    </div>
    <div class="modal-footer">
      <h3>Modal Footer</h3>
    </div>
  </div>

</div>

Обработка динамического содержимого для модального в зависимости от нажатой кнопки:

const data = [{
    title: "Modal Header 1",
    content: ["Some text in the Modal Body 1", "Some other text 1..."],
    footer: "Modal Footer 1"
  },
  {
    title: "Modal Header 2",
    content: ["Some text in the Modal Body 2", "Some other text 2..."],
    footer: "Modal Footer 2"
  },
  {
    title: "Modal Header 3",
    content: ["Some text in the Modal Body 3", "Some other text 3..."],
    footer: "Modal Footer 3"
  }
]

function dynamicModalContent(i) {
  const {
    title,
    content,
    footer
  } = data[i];

  const body = content.map(c => '<p>${c}</p>').join("");

  return '
    <!-- Modal content -->
    <div class="modal-content">
      <div class="modal-header">
        <span class="close">&times;</span>
        <h2>${title}</h2>
      </div>
      <div class="modal-body">
        ${body}
      </div>
      <div class="modal-footer">
        <h3>${footer}</h3>
      </div>
    </div>
    '
}

// Get the modal
var modal = document.getElementById('detailmodal');

// Get the button that opens the modal
var btns = document.querySelectorAll(".modalbutton");

window.addEventListener("click", function(e){
   const tar = e.target;
   if(tar.classList.contains('close')){
      modal.style.display = "none";
   }
});

// When the user clicks the button, open the modal 
btns.forEach((btn, i) => {
  btn.addEventListener("click", function() {
    modal.innerHTML = dynamicModalContent(i);
    modal.style.display = "block";
  });
});


// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
/* The Modal (background) */

.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4);
  /* Black w/ opacity */
}


/* Modal Content */

.modal-content {
  position: relative;
  float: right;
  background-color: #fefefe;
  margin: auto;
  padding: 0;
  border: 1px solid #888;
  max-width: 850px;
  width: 100%;
  height: 100%;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  -webkit-animation-name: animatetop;
  -webkit-animation-duration: 0.4s;
  animation-name: animatetop;
  animation-duration: 0.8s
}


/* Add Animation */

@-webkit-keyframes animatetop {
  from {
    right: -100px;
    opacity: 0
  }
  to {
    right: 0;
    opacity: 1
  }
}

@keyframes animatetop {
  from {
    right: -100px;
    opacity: 0
  }
  to {
    right: 0;
    opacity: 1
  }
}
<button class="modalbutton">Open Modal</button>

<button class="modalbutton">Open Modal</button>

<button class="modalbutton">Open Modal</button>

<!-- The Modal -->
<div id="detailmodal" class="modal">

</div>
  • 0
    Это тоже сработало! Если я хочу распространять различный контент в модальном режиме в зависимости от того, какую кнопку вы нажимаете, я бы написал отдельную функцию для этого? (думайте об этом как о лайтбоксе, и я хочу нажать на кнопку. Каждая из трех кнопок содержит различный контент с идентификатором detailmodal)
  • 0
    @Coleman проверить редактировать.
0

Сначала удалите дубликаты идентификаторов, затем вместо этого вы можете использовать существующие классы modalbutton с document.getElementsByClassName("modalbutton"). Чтобы прикрепить всплывающую функцию к каждой кнопке, вы можете зациклить их с помощью:

for (let i = 0; i < btn.length; i++) {
  btn[i].onclick = function() {
    modal.style.display = "block";
  }
}

Это можно увидеть в следующем:

// Get the modal
var modal = document.getElementById('detailmodal');


// Get the button that opens the modal
var btn = document.getElementsByClassName("modalbutton");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the buttons open the modal 
for (let i = 0; i < btn.length; i++) {
  btn[i].onclick = function() {
    modal.style.display = "block";
  }
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
/* The Modal (background) */

.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4);
  /* Black w/ opacity */
}


/* Modal Content */

.modal-content {
  position: relative;
  float: right;
  background-color: #fefefe;
  margin: auto;
  padding: 0;
  border: 1px solid #888;
  max-width: 850px;
  width: 100%;
  height: 100%;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  -webkit-animation-name: animatetop;
  -webkit-animation-duration: 0.4s;
  animation-name: animatetop;
  animation-duration: 0.8s
}


/* Add Animation */

@-webkit-keyframes animatetop {
  from {
    right: -100px;
    opacity: 0
  }
  to {
    right: 0;
    opacity: 1
  }
}

@keyframes animatetop {
  from {
    right: -100px;
    opacity: 0
  }
  to {
    right: 0;
    opacity: 1
  }
}
<button class="modalbutton">Open Modal</button>

<button class="modalbutton">Open Modal</button>

<button class="modalbutton">Open Modal</button>

<!-- The Modal -->
<div id="detailmodal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">&times;</span>
      <h2>Modal Header</h2>
    </div>
    <div class="modal-body">
      <p>Some text in the Modal Body</p>
      <p>Some other text...</p>
    </div>
    <div class="modal-footer">
      <h3>Modal Footer</h3>
    </div>
  </div>

</div>

Однако следует отметить, что вы, вероятно, хотите, каждая кнопку, чтобы вызвать другую модальность, который нужен будет пользовательской функция для каждой кнопки (или параметр функции передается в родовую функцию).

  • 0
    Круто, это исправило мою проблему! Так что если мне нужно, чтобы каждый «detailmodal» (фактическое всплывающее окно) отличался в зависимости от клика, мне придется написать для этого еще одну функцию?

Ещё вопросы

Сообщество Overcoder
Наверх
Меню