我试图在用户单击我页面上的某个元素时显示一个弹出窗口。我拥有弹出窗口正常工作的所有功能;但是,我无法让函数弹出与指定类名匹配的每个元素。我的代码如下:
<script>
function descPop () {
// Description pop-up
// Get the modal
var modalprod = document.getElementById('myModalTwo');
// Get the button that opens the modal
var btnprod = document.getElementsByClassName("add-but")[0];
// Get the <span> element that closes the modal
var spanprod = document.getElementsByClassName("prod-close")[0];
// When the user clicks on the button, open the modal
btnprod.onclick = function() {
modalprod.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
spanprod.onclick = function() {
modalprod.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modalprod) {
modalprod.style.display = "none";
}
}
}
</script>
现在,我知道当前这段代码正在将索引 0 分配给 var btnprod;因此,它只会在您单击第一个与类名“add-but”匹配的元素时弹出。我如何分配和访问所有元素,以便每个带有类名“add-but”的标签都会弹出窗口?
谢谢
解决方案:
function descPop () {
// Description pop-up
// Get the modal
var modalprod = document.getElementById('myModalTwo');
// Get the button that opens the modal
var btnprod = document.getElementsByClassName("add-but");
// Get the <span> element that closes the modal
var spanprod = document.getElementsByClassName("prod-close");
// When the user clicks on the button, open the modal
for (var i = 0; i < btnprod.length; i++) {
btnprod[i].onclick = function() {
modalprod.style.display = "block";
}
}
// When the user clicks on <span> (x), close the modal
for (var i = 0; i < spanprod.length; i++) {
spanprod[i].onclick = function() {
modalprod.style.display = "none";
}
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modalprod) {
modalprod.style.display = "none";
}
}
}
最佳答案
如果 Jquery 不是一个选项,您可以遍历 HtmlCollection 来执行此操作:
var btnprod = document.getElementsByClassName("add-but"); // <- this gives you a HTMLCollection
for (var i = 0; i < btnprod.length; i++) {
btnprod[i].onclick = function() {
modalprod.style.display = "block";
}
}
关于javascript - 如何在具有相同类名的所有元素上调用 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41137872/