HTML页面多按钮触发同一模态框问题(不使用ID)
解决多个按钮触发同一模态窗口的问题
你的问题出在仅为第一个按钮绑定了点击事件:getElementsByClassName返回的是所有匹配元素的集合,但你只取了索引[0]的第一个元素,其他按钮没有绑定触发逻辑。下面是修正后的完整实现:
核心修改后的JavaScript代码
// 获取模态框 var modal = document.getElementsByClassName("myModal")[0]; // 获取所有打开模态框的按钮 var btns = document.getElementsByClassName("myBtn"); // 获取关闭图标元素 var span = document.getElementsByClassName("close")[0]; // 遍历所有按钮,为每个按钮绑定点击事件 for (var i = 0; i < btns.length; i++) { btns[i].onclick = function() { modal.style.display = "block"; } } // 点击关闭图标关闭模态框 span.onclick = function() { modal.style.display = "none"; } // 点击模态框外部区域关闭 window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } // 底部关闭按钮的点击逻辑 function closePopup() { modal.style.display = "none"; }
关键调整点
- 将
var btn = document.getElementsByClassName("myBtn")[0];改为var btns = document.getElementsByClassName("myBtn");,获取所有按钮元素 - 通过
for循环遍历按钮集合,为每个按钮单独绑定打开模态框的点击事件
完整可运行代码示例
HTML
<button class="myBtn errormodalbutton">Open Modal 1</button> <hr> <button class="myBtn errormodalbutton">Open Modal 2</button> <hr> <button class="myBtn errormodalbutton">Open Modal 3</button> <hr> <button class="myBtn errormodalbutton">Open Modal 4</button> <div class="myModal modal"> <div class="modal-content"> <span class="close">×</span> <h3 style="text-align:center">Test</h3> <p>Some text.</p> <div class="close-button"> <button type="button" class="right" onclick="closePopup()">Close</button> </div> </div> </div>
CSS
.modal { display: none; position: fixed; z-index: 1; padding-top: 100px; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgb(0, 0, 0); background-color: rgba(0, 0, 0, 0.4); } .modal-content { font-style: normal; width: 600px; height: 200px; background: #fff; border-radius: 6px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: left; padding: 0 0 5px 10px; color: #333; } .errormodalbutton { background: none !important; border: none; padding: 0 !important; font-family: arial, sans-serif; color: #069; text-decoration: underline; cursor: pointer; } .close-button { padding: 0 10px 10px 0; vertical-align: baseline; } .close-button button { position: fixed; bottom: 10px; right: 10px; float: right; font-style: normal; background: #6C757D; color: #fff; border: 0; outline: none; border-radius: 2px; cursor: pointer; }
修改后所有按钮都能正常触发模态框显示,原有关闭逻辑保持不变即可。
内容的提问来源于stack exchange,提问作者Dazzler
相关产品推荐
相关产品推荐

