繁体   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