Я попытался создать всплывающее модальное окно для моей страницы резюме, и сработало только мое первое всплывающее модальное окно, оба модальных окна 2 и 3 не всплывали, когда я пытался нажать кнопку для каждого модального окна. Я попытался присвоить модальному «id» уникальные номера, но это не сработало, и я попытался заменить имена для последних двух модальных окон, но это не сработало.
Должен ли я реализовать функцию onClick или что мне не хватает?
const modal = document.querySelector("#modal");
const openModal = document.querySelector(".open-button");
const closeModal = document.querySelector(".close-button");
openModal.addEventListener("click", () => {
modal.showModal();
});
closeModal.addEventListener("click", () => {
modal.close();
}); .modal {
padding: 5em;
max-width: 100ch;
}
.modal2 {
padding: 1em;
margin: 5em;
max-width: 100ch;
}
.modal3 {
padding: 1em;
max-width: 50ch;
} <dialog class = "modal" id = "modal">
<h2>Bank Project Info</h2>
<p>I have been a part of a group were we created a online bank in which users could go in and borrow and deposit money. They could create their own account and log in and out on their own accord.</p>
<button class = "button close-button">close</button>
</dialog>
<dialog class = "modal" id = "modal2">
<h2>School Project Info</h2>
<p>Me and some other classmates created a school project were we created a console application that enabled us to add both students and teacher into the application. We could add student information, who their teachers were and how many students each class had.</p>
<button class = "button close-button">close</button>
</dialog>
<dialog class = "modal" id = "modal3">
<h2>ASP.NET Project Info</h2>
<p>We were tasked to build a administration application for a webshop, it was suppose to be a create with a seperate admin functionality for the website. Was a very interesting webpage that me and my group created, we used HTML, CSS and JavaScript for the project.</p>
<button class = "button close-button">close</button>
</dialog>Каждая кнопка имеет одно всплывающее модальное событие.
ГДЕ находится код JavaScript для modal2 и modal3?
Код для modal2 и 3 находится в HTML, но вы говорите, что мне нужно добавить еще один «const Open Modal» в JS как для модального 2, так и для 3?
Да.... Ваш код нацелен только на ОДНУ "кнопку .open" на странице. Он не волшебным образом связывается со всеми из них.
Было бы лучше добавить его в отдельный файл JS или можно добавить дополнительный модальный код в первый?
Было бы лучше сделать это одним из способов, которые я предлагаю в качестве ответа.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Ваш код работает только с одним элементом, вам нужен код для каждого из них.
Решение для копирования/вставки - сделать несколько копий для каждой кнопки. Это не здорово.
Лучшим решением является код, который зацикливается на коллекции html и связывает события.
// get all the buttons that open the modals
const openButtons = document.querySelectorAll("[data-opens]");
// loop over the buttons
openButtons.forEach(function(btn) {
// get the selector
var modalSelector = btn.dataset.opens;
btn.addEventListener("click", function() {
document.querySelector(modalSelector).showModal();
});
});
//get all the close buttons and attach events
// get all the buttons that open the modals
const closeButtons = document.querySelectorAll(".close-button");
closeButtons.forEach(function(btn) {
btn.addEventListener("click", function() {
// find the parent that is a modal element and close it
btn.closest('.modal').close();
});
});.modal {
padding: 5em;
max-width: 100ch;
}
.modal2 {
padding: 1em;
margin: 5em;
max-width: 100ch;
}
.modal3 {
padding: 1em;
max-width: 50ch;
}<dialog class = "modal" id = "modal">
<h2>Bank Project Info</h2>
<p>I have been a part of a group were we created a online bank in wich users could go in and borrow and deposit money. They could create their own account and log in and out on their own accord.</p>
<button class = "button close-button">close</button>
</dialog>
<dialog class = "modal" id = "modal2">
<h2>School Project Info</h2>
<p>Me and some other classmates created a school project were we created a console application that enabled us to add both students and teacher into the application. We could add student information, who their teachers were and how many students each class
had.</p>
<button class = "button close-button">close</button>
</dialog>
<dialog class = "modal" id = "modal3">
<h2>ASP.NET Project Info</h2>
<p>We were tasked to build a administration application for a webshop, it was suppose to be a create with a seperate admin functionality for the website. Was a very interesting webpage that me and my group created, we used HTML, CSS and JavaScript for
the project.</p>
<button class = "button close-button">close</button>
</dialog>
<button data-opens = "#modal">1</button>
<button data-opens = "#modal2">2</button>
<button data-opens = "#modal3">3</button>Другим решением является делегирование событий.
// Bind event to an element that contains all of the modals and open buttons
document.body.addEventListener("click", function(evt) {
// get was clicked
const elem = event.target;
// determine if we clicked the open button or the close button
if (elem.matches('[data-opens]')) {
var modalSelector = elem.dataset.opens;
document.querySelector(modalSelector).showModal();
} else if (elem.matches('.close-button')) {
elem.closest(".modal").close();
}
});.modal {
padding: 5em;
max-width: 100ch;
}
.modal2 {
padding: 1em;
margin: 5em;
max-width: 100ch;
}
.modal3 {
padding: 1em;
max-width: 50ch;
}<dialog class = "modal" id = "modal">
<h2>Bank Project Info</h2>
<p>I have been a part of a group were we created a online bank in wich users could go in and borrow and deposit money. They could create their own account and log in and out on their own accord.</p>
<button class = "button close-button">close</button>
</dialog>
<dialog class = "modal" id = "modal2">
<h2>School Project Info</h2>
<p>Me and some other classmates created a school project were we created a console application that enabled us to add both students and teacher into the application. We could add student information, who their teachers were and how many students each class
had.</p>
<button class = "button close-button">close</button>
</dialog>
<dialog class = "modal" id = "modal3">
<h2>ASP.NET Project Info</h2>
<p>We were tasked to build a administration application for a webshop, it was suppose to be a create with a seperate admin functionality for the website. Was a very interesting webpage that me and my group created, we used HTML, CSS and JavaScript for
the project.</p>
<button class = "button close-button">close</button>
</dialog>
<button data-opens = "#modal">1</button>
<button data-opens = "#modal2">2</button>
<button data-opens = "#modal3">3</button>БОЛЬШОЕ спасибо, первое решение творило чудеса, я не могу выразить, насколько я благодарен, я потратил много времени, пытаясь понять это. Удачного дня
Итак, у вас есть несколько событий для каждой кнопки и модального окна? Ваш код
const openModal = document.querySelector(".open-button");выбирает первый элемент с найденным классом, он не получает их все и не прикрепляет события.