簡體   English   中英

getElementById的多個ID

[英]Multiple ID's for getElementById

參見以下代碼:

https://www.w3schools.com/code/tryit.asp?filename=FFFP03OMYA94

我有兩個按鈕(甚至更多)。 當我單擊第一個按鈕時,它應顯示第一個div 當我單擊第二個按鈕時,它應該顯示另一個div 這只是我的問題的一小段。 我想要實現的是,當我單擊按鈕時,它應該使用傳遞的ID打開div 通常我有一個唯一的ID,所以我也可以這樣保存ID:

<div id="myModal+${person.id}" class="modal">

我的問題是:如何將ID傳遞給javaScript並為傳遞的ID打開特定的div

您可以將此ID存儲在data-*屬性中,如下所示:

 // Here, I used a class for the buttons, since there are multiple ones var btns = document.getElementsByClassName('myBtn'), // These variables will hold the currently open modal and close button modal, closeBtn; // For each button for(var i=0; i<btns.length; i++) { // On click btns[i].addEventListener('click', function(){ // Get the modal ID var modalId = this.getAttribute('data-modal'); // Retrieve the corresponding modal modal = document.getElementById(modalId); // Retrieve the close button closeBtn = modal.querySelector('.close'); // Show the modal modal.style.display = "block"; }, false); } window.addEventListener('click', function(event) { // If we clicked on the backdrop or the close button if (event.target == modal || event.target == closeBtn) { // Hide the modal modal.style.display = "none"; } }, false); 
 .modal{display:none;position:fixed;z-index:1;padding-top:100px;left:0;top:0;width:100%;height:100%;overflow:auto;background-color:#000;background-color:rgba(0,0,0,.4)}.modal-content{background-color:#fefefe;margin:auto;padding:20px;border:1px solid #888;width:80%}.close{color:#aaa;float:right;font-size:28px;font-weight:700}.close:focus,.close:hover{color:#000;text-decoration:none;cursor:pointer} 
 <h2>Modal Example</h2> <button class="myBtn" data-modal="myModalA">Open Modal A</button> <div id="myModalA" class="modal"><div class="modal-content"><span class="close">&times;</span><p>This is myModalA</p></div></div> <button class="myBtn" data-modal="myModalB">Open Modal B</button> <div id="myModalB" class="modal"><div class="modal-content"><span class="close">&times;</span><p>This is myModalB</p></div></div> <button class="myBtn" data-modal="myModalC">Open Modal C</button> <div id="myModalC" class="modal"><div class="modal-content"><span class="close">&times;</span><p>This is myModalC</p></div></div> <button class="myBtn" data-modal="myModalD">Open Modal D</button> <div id="myModalD" class="modal"><div class="modal-content"><span class="close">&times;</span><p>This is myModalD</p></div></div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM