Я работал на профессиональном веб-сайте, который будет включать в себя раздел портфолио. Я хочу, чтобы в портфеле было несколько миниатюр — при нажатии на каждую миниатюру открывается модальное окно с дополнительной информацией по этому вопросу. Проблема, с которой я сталкиваюсь, заключается в том, что открывается только первый модал. Второй не работает (и я хотел бы добавить несколько из них в идеале). Я уже несколько месяцев читаю онлайн-справку и пробую разные решения. Пока ничего не получалось. Я выложу код здесь. Извиняюсь за длину, блочные цвета и отсутствие изображений в этой версии. Но я думаю, вы поняли идею. Нажмите на кнопку с пометкой «Пользователи, проводящие сортировку карт», чтобы увидеть возникшую проблему. Любая помощь приветствуется!

// Get the modal var modal = document.getElementsByClassName("modal")[0]; // Get the button that opens the modal var btn = document.getElementsByClassName("button")[0]; // Get the {amp}lt;span{amp}gt; element that closes the modal var span = document.getElementsByClassName("close")[0]; // When the user clicks on the button, open the modal btn.onclick = function() { modal.style.display = "block"; } // When the user clicks on {amp}lt;span{amp}gt; (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"; } } // Cache selectors var lastId, topMenu = $("#nav-links"), topMenuHeight = topMenu.outerHeight() 15, // All list items menuItems = topMenu.find("a"), // Anchors corresponding to menu items scrollItems = menuItems.map(function(){ var item = $($(this).attr("href")); if (item.length) { return item; } }); // Bind click handler to menu items // so we can get a fancy scroll animation menuItems.click(function(e){ var href = $(this).attr("href"), offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight 1; $('html, body').stop().animate({ scrollTop: offsetTop }, 300); e.preventDefault(); }); // Bind to scroll $(window).scroll(highlightNav); $(window).ready(highlightNav); function highlightNav(){ // Get container scroll position var fromTop = $(this).scrollTop() topMenuHeight; // Get id of current scroll item var cur = scrollItems.map(function(){ if ($(this).offset().top {amp}lt; fromTop) return this; }); // Get the id of the current element cur = cur[cur.length-1]; var id = cur {amp}amp;{amp}amp; cur.length ? cur[0].id : ""; if (lastId !== id) { lastId = id; // Set/remove active class menuItems .parent().removeClass("active") .end().filter("[href='#" id "']").parent().addClass("active"); } } 
 *{ margin: 0px; padding: 0px; box-sizing: border-box; } @media screen and (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } } #logo { max-width: 10%; height: auto; padding: 1vh; } nav { display: flex; position: fixed; z-index: 1; /* Stay on top */ top: 0; /* Stay at the top */ justify-content: space-around; align-items: center; min-height: 15%; background-color: grey; font-family: 'Red Hat Display', sans-serif; } .navname { color: #ECEAEA; text-transform: uppercase; letter-spacing: 0.4vw; font-size: 2.2vw; font-family: 'Volkhov', serif; } #nav-links { display: flex; justify-content: space-around; width: 38%; } #nav-links li { list-style: none; } #nav-links a { color: #ECEAEA; text-decoration: none;s font-weight: bold; letter-spacing: 0.2vh; font-size: 1.2vw; -webkit-transition: 50ms all ease-out; -moz-transition: 50ms all ease-out; transition: 50ms all ease-out; } #nav-links li.active a { color: #EADA15; } #mainpage { padding-left: 1vh; background-color: #EADA15; padding-top: 1% } #about { padding-top: 14%; } #portfolio, #experience, #education { padding-top: 12% } .column1 { width: 31%; float: left; margin: 1%; } .column2 { width: 64%; float: right; margin: 1%; } #portrait { max-width: 100%; height: auto; padding: 0vh; } .bodytext { font-family: 'Red Hat Text', sans-serif; font-size: 1.5vw; line-height: 2vw; text-align: justify; vertical-align: middle; } .divider { width: 100%; overflow: auto; } .column3, .column4, .column5 { width: 29%; float: left; margin: 1%; } #portfolio { background-color: blue; overflow: auto; } button { background-color: blue; border: 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 */ -webkit-transition: all 3s; -moz-transition: all 3s; transition: all 3s; } /* Modal Content/Box */ .modal-content { background-color: #fefefe; margin: 10% auto; /* 15% from the top and centered */ padding: 20px; border: 1px solid #888; width: 60%; /* Could be more or less, depending on screen size */ } /* The Close Button */ .close { color: #aaa; float: right; font-size: 28px; font-weight: bold; } .close:hover, .close:focus { color: black; text-decoration: none; cursor: pointer; } .portfolioimage { cursor: pointer; -webkit-filter: brightness(100%); } .portfolioimage:hover { -webkit-filter: brightness(70%); -webkit-transition: all 500ms ease; -moz-transition: all 500ms ease; -o-transition: all 500ms ease; -ms-transition: all 500ms ease; transition: all 500ms ease; } @media screen and (max-width:1024px){ .nav-links a { font-size: 1.5vw; } } @media screen and (max-width:768px){ nav { min-height: 20vh; } #logo { max-width: 15%; height: auto; padding: 1vh; } .navname { font-size: 3vh; } .nav-links{ display: block; text-align: left; width: 15% } .nav-links li { line-height: 4vh; } .nav-links a { font-size: 2vh; padding: 0.5vh; } #about { padding-top: 11vh; } .bodytext { font-size: 2.5vw; line-height: 3vw; text-align: left; } } /* Modal Content */ .modal-content { position: relative; animation-name: animatetop; animation-duration: 1.4s } /* Add Animation */ @keyframes animatetop { from {top: -500px; opacity: 0} to {top: 0; opacity: 1} } 
 {amp}lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"{amp}gt;{amp}lt;/script{amp}gt; {amp}lt;!doctype html{amp}gt; {amp}lt;html lang="en"{amp}gt; {amp}lt;head{amp}gt; {amp}lt;meta charset="utf-8"{amp}gt; {amp}lt;meta name="viewport" content="width=device-width, initial-scale=1.0"{amp}gt; {amp}lt;link href="styles.css" rel="stylesheet"{amp}gt; {amp}lt;script type="text/javascript" src="jquery-3.4.1.js"{amp}gt;{amp}lt;/script{amp}gt; {amp}lt;title{amp}gt;Adam McBride-Smith{amp}lt;/title{amp}gt; {amp}lt;/head{amp}gt; {amp}lt;body{amp}gt; {amp}lt;nav{amp}gt; {amp}lt;img id="logo" src="logo.png" alt="A magipie sits on an wire-rimmed AMS."/{amp}gt; {amp}lt;div class="navname"{amp}gt; {amp}lt;h1{amp}gt;Adam McBride-Smith{amp}lt;/h1{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;ul id="nav-links"{amp}gt; {amp}lt;li{amp}gt; {amp}lt;a href="#about"{amp}gt;About{amp}lt;/a{amp}gt; {amp}lt;/li{amp}gt; {amp}lt;li{amp}gt; {amp}lt;a href="#portfolio"{amp}gt;Portfolio{amp}lt;/a{amp}gt; {amp}lt;/li{amp}gt; {amp}lt;li{amp}gt; {amp}lt;a href="#experience"{amp}gt;Experience{amp}lt;/a{amp}gt; {amp}lt;/li{amp}gt; {amp}lt;li{amp}gt; {amp}lt;a href="#education"{amp}gt;Education{amp}lt;/a{amp}gt; {amp}lt;/li{amp}gt; {amp}lt;/ul{amp}gt; {amp}lt;/nav{amp}gt; {amp}lt;div id="mainpage"{amp}gt; {amp}lt;div id="about"{amp}gt; {amp}lt;div class="about column1"{amp}gt; {amp}lt;h4 id="bio" class="bodytext"{amp}gt;I'm a technical communicator with a background in education and a passion for creative problem solving. Whether conducting user research, designing accessible interfaces, drafting flow diagrams, or writing documentation, I believe that collective efforts often produce the best results, and that technology can help show the way to a more open, compassionate, and democratic future. {amp}lt;/h4{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;div class="about column2"{amp}gt; {amp}lt;img id="portrait" src="portrait.jpg" alt="A picture of Adam smiling and wearing headphones"/{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;div id="div1" class="divider"{amp}gt;{amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;div id="portfolio"{amp}gt; {amp}lt;h4{amp}gt;Portfolio{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;div class="portfolio column3"{amp}gt; {amp}lt;div id="firstModal"{amp}gt; {amp}lt;!-- Trigger/Open The Modal --{amp}gt; {amp}lt;button id="myBtn1" class="button"{amp}gt;{amp}lt;img id="cardsortthumb" class="portfolioimage" src="cardsort.png" alt="Users conducting a card sort" width="100%" height="auto" /{amp}gt;{amp}lt;/button{amp}gt; {amp}lt;!-- The Modal --{amp}gt; {amp}lt;div id="myModal1" class="modal"{amp}gt; {amp}lt;!-- Modal content --{amp}gt; {amp}lt;div class="modal-content"{amp}gt; {amp}lt;span class="close"{amp}gt;{amp}amp;times;{amp}lt;/span{amp}gt; {amp}lt;h2{amp}gt;Web Page Usability Testing{amp}lt;/h2{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h3{amp}gt;Competencies: Usability Testing, Data Analysis, Content Management{amp}lt;br /{amp}gt; Personal Characteristics: Collaboration, Critical Thinking{amp}lt;br /{amp}gt; Tools: MS Excel{amp}lt;/h3{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;p{amp}gt;As a project for a class on research methods at Portland State University, I participated in exploratory usability testing of a web page. The page was designed to help students and faculty in the Professional and Technical Writing Program get answers to their questions about the program. The purpose of the study was to determine whether the information categories used by the page aligned with user preferences.{amp}lt;/p{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;img id="cardsortfull" src="cardsort.png" alt="Users conducting a card sort" width="100%" height="auto" /{amp}gt;{amp}lt;br /{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;p{amp}gt;We started our research by conducting both open and closed {amp}lt;strong{amp}gt;card sorts{amp}lt;/strong{amp}gt;. During our closed card sort, printed category cards that matched the actual site menu were distributed among the groups of users. Subcategory cards were also distributed. Our test participants then grouped the subcategory cards under their preferred headings. Data from each card sort was collected and collated to show the user preferences of the group as a whole. {amp}lt;/p{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;img id="simmat" src="simmat.jpg" alt="An Excell spreadsheet showing a similarity matrix" width="100%" height="auto" /{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;p{amp}gt;Following the card sorts, I participated in creating a {amp}lt;strong{amp}gt;similarity matrix{amp}lt;/strong{amp}gt; to describe the groupings preferred by our card sort participants, and to compare those preferences with the actual information design of the MPTW web page. We were able to highlight areas where the site aligned with user expectations, but also important areas where it was not aligned. Analyzing our data against the actual site brought to light some of the idiosycrasies that can result when legacy content is updated with more recent content, such as information “islands,” and inconsistent formatting. At the conclusion of our study, we compiled our findings and presented them to the head of the MPTW program.{amp}lt;/p{amp}gt; {amp}lt;br /{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;div class="portfolio column4"{amp}gt; {amp}lt;div id="secondModal"{amp}gt; {amp}lt;!-- Trigger/Open The Modal --{amp}gt; {amp}lt;button id="myBtn2" class="button"{amp}gt;{amp}lt;img id="personathumb" class="portfolioimage" src="persona2.jpg" alt="Users conducting a card sort" width="100%" height="auto" /{amp}gt;{amp}lt;/button{amp}gt; {amp}lt;!-- The Modal --{amp}gt; {amp}lt;div id="myModal2" class="modal"{amp}gt; {amp}lt;!-- Modal content --{amp}gt; {amp}lt;div class="modal-content"{amp}gt; {amp}lt;span class="close"{amp}gt;{amp}amp;times;{amp}lt;/span{amp}gt; {amp}lt;h2{amp}gt;Web Page Usability Testing{amp}lt;/h2{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h3{amp}gt;Competencies: Usability Testing, Data Analysis, Content Management{amp}lt;br /{amp}gt; Personal Characteristics: Collaboration, Critical Thinking{amp}lt;br /{amp}gt; Tools: MS Excel{amp}lt;/h3{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;p{amp}gt;As a project for a class on research methods at Portland State University, I participated in exploratory usability testing of a web page. The page was designed to help students and faculty in the Professional and Technical Writing Program get answers to their questions about the program. The purpose of the study was to determine whether the information categories used by the page aligned with user preferences.{amp}lt;/p{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;img id="persona1" src="persona1.jpg" alt="Users conducting a card sort" width="100%" height="auto" /{amp}gt;{amp}lt;br /{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;p{amp}gt;We started our research by conducting both open and closed {amp}lt;strong{amp}gt;card sorts{amp}lt;/strong{amp}gt;. During our closed card sort, printed category cards that matched the actual site menu were distributed among the groups of users. Subcategory cards were also distributed. Our test participants then grouped the subcategory cards under their preferred headings. Data from each card sort was collected and collated to show the user preferences of the group as a whole. {amp}lt;/p{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;img id="persona2" src="persona2.jpg" alt="An Excell spreadsheet showing a similarity matrix" width="100%" height="auto" /{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;p{amp}gt;Following the card sorts, I participated in creating a {amp}lt;strong{amp}gt;similarity matrix{amp}lt;/strong{amp}gt; to describe the groupings preferred by our card sort participants, and to compare those preferences with the actual information design of the MPTW web page. We were able to highlight areas where the site aligned with user expectations, but also important areas where it was not aligned. Analyzing our data against the actual site brought to light some of the idiosycrasies that can result when legacy content is updated with more recent content, such as information “islands,” and inconsistent formatting. At the conclusion of our study, we compiled our findings and presented them to the head of the MPTW program.{amp}lt;/p{amp}gt; {amp}lt;br /{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;div class="portfolio column5"{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;div id="div2" class="divider"{amp}gt;{amp}lt;/div{amp}gt; {amp}lt;div id="experience"{amp}gt; {amp}lt;h4{amp}gt;Experience{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;div id="education"{amp}gt; {amp}lt;h4{amp}gt;Education{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;h4{amp}gt;#{amp}lt;/h4{amp}gt;{amp}lt;br /{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;script type="text/javascript" src="script.js"{amp}gt;{amp}lt;/script{amp}gt; {amp}lt;/body{amp}gt; {amp}lt;/html{amp}gt; 

А. Макбрайд

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

Правила поведения

,

var btn = document.getElementsByClassName("button")[0]; в этой строке упоминается только выбор первого элемента ( [0] ) из списка, поэтому он работает только для первого элемента.

 var btn = document.getElementsByClassName("button")[0]; btn.onclick = function() { modal.style.display = "block"; } 

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

 var btn = document.getElementsByClassName("button"); btn.forEach(b={amp}gt;{b.onclick = function() { modal.style.display = "block"; }}) 

также сделайте то же самое, если у вас есть несколько модалов.

@ серое лицо, это имеет смысл. Я попытался реализовать это, и теперь ни один модальный режим не работает, хотя вполне возможно, что я сделал это неправильно. Я также получаю предупреждение в Dreamweaver, что в строке 12 есть «неожиданный токен».

 // Get the modal var modal = document.getElementsByClassName("modal"); // Get the button var btn = document.getElementsByClassName("button"); // Get the {amp}lt;span{amp}gt; element that closes the modal var span = document.getElementsByClassName("close"); // When the user clicks on the button, open the modal btn.forEach(b={amp}gt;{b.onclick = function() { modal.style.display = "block"; }}) // When the user clicks on {amp}lt;span{amp}gt; (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"; } } 
А. Макбрайд

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

Правила поведения

,