Всплывающее модальное окно

Я попытался создать всплывающее модальное окно для моей страницы резюме, и сработало только мое первое всплывающее модальное окно, оба модальных окна 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>

Итак, у вас есть несколько событий для каждой кнопки и модального окна? Ваш код const openModal = document.querySelector(".open-button"); выбирает первый элемент с найденным классом, он не получает их все и не прикрепляет события.

epascarello 31.03.2023 14:22

Каждая кнопка имеет одно всплывающее модальное событие.

Filip 31.03.2023 14:24

ГДЕ находится код JavaScript для modal2 и modal3?

epascarello 31.03.2023 14:25

Код для modal2 и 3 находится в HTML, но вы говорите, что мне нужно добавить еще один «const Open Modal» в JS как для модального 2, так и для 3?

Filip 31.03.2023 14:28

Да.... Ваш код нацелен только на ОДНУ "кнопку .open" на странице. Он не волшебным образом связывается со всеми из них.

epascarello 31.03.2023 14:29

Было бы лучше добавить его в отдельный файл JS или можно добавить дополнительный модальный код в первый?

Filip 31.03.2023 14:43

Было бы лучше сделать это одним из способов, которые я предлагаю в качестве ответа.

epascarello 31.03.2023 14:44
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
1
7
50
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Ваш код работает только с одним элементом, вам нужен код для каждого из них.

Решение для копирования/вставки - сделать несколько копий для каждой кнопки. Это не здорово.

Лучшим решением является код, который зацикливается на коллекции 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>

БОЛЬШОЕ спасибо, первое решение творило чудеса, я не могу выразить, насколько я благодарен, я потратил много времени, пытаясь понять это. Удачного дня

Filip 31.03.2023 16:33

Другие вопросы по теме