getElementById的多个ID

时间:2017-05-09 19:06:20

标签: javascript jquery html jsp

请参阅此代码:

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

1 个答案:

答案 0 :(得分:1)

您可以将此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>