【发布时间】:2016-12-14 08:23:27
【问题描述】:
我试图在用户单击我页面上的元素时显示一个弹出窗口。我的弹出窗口的所有功能都可以正常工作;但是,我无法为每个与指定类名匹配的元素弹出函数。我的代码如下:
<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";
}
}
}
【问题讨论】:
-
var $btnprod = $(".add-but") 并绑定一个像 $btnProd.on("click", function() {// YOUR CODE})l .... .....................使用jquery来做
-
你的代码是 javascript 但你标记了 jquery,试试 jquery 让生活更轻松
-
你说得对,对不起,我不是故意给 jquery 打标签的
标签: javascript jquery html