我正在尝试在一个页面上创建多个弹出窗口,这些弹出窗口会在单击对应于它们的按钮后出现。我目前将它们放在同一个类(class),如下所示:
<div>
<!-- Popup -->
<div class="popup">
<div class="popup-content">
Some text here
</div>
</div>
<!-- Button -->
<img src="button.png" class="popup-button"/>
</div>
问题是我很难用我的 javascript 代码访问单个元素。我不确定用什么来替换手动数组访问( [0] 现在)。
<script>
// Get the popup
var popup = document.getElementsByClassName("popup")[0];
// Get the button that opens the popup
var btn = document.getElementsByClassName("popup-button")[0];
// When the user clicks the button, open the popup (hidden by default)
btn.onclick = function() {
popup.style.display = "block";
}
</script>
现在,我可以创建多个脚本并为每个元素手动访问数组,但当然我正在尝试使其自动化,以便脚本将根据单击的按钮运行。假设,如果单击第 5 个按钮,则会出现第 5 个弹出窗口。谢谢你!
最佳答案
在 Javascript 中链接多个元素的最佳方式是通过 the dataset of the elements 使用 id .
// Get the popup's btn list
var popupsBtn = document.getElementsByClassName("popup-btn");
// Go through the popup's btn list
for (var i = 0; i < popupsBtn.length; i++) {
// Define the onclick event on popup's btn
popupsBtn[i].onclick = function() {
// Get the popup associated to the btn with the data-popup-id
var popup = document.getElementById("popup-" + this.dataset.popupId);
// Use a class to toggle popup visible or not
popup.classList.toggle("visible");
}
}
.popup {
display: none;
}
.popup.visible {
display: block;
}
<!DOCUMENT html>
<html>
<head></head>
<body>
<div>
<div id="popup-1" class="popup">popup 1 here</div>
<img src="button.png" class="popup-btn" data-popup-id="1" />
</div>
<div>
<div id="popup-2" class="popup">popup 2 here</div>
<img src="button.png" class="popup-btn" data-popup-id="2" />
</div>
<div>
<div id="popup-3" class="popup">popup 3 here</div>
<img src="button.png" class="popup-btn" data-popup-id="3" />
</div>
</body>
</html>
关于javascript - 使用 JS 通过 getElementsByClassName() 访问多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51438066/