我正在尝试为我的网站上的图像创建自己的灯箱。是的,我知道有 lightbox2 并且它是免费的,但我喜欢挑战。我在灯箱本身上遇到点击事件问题,我试图让它删除灯箱,但点击事件似乎没有注册,并且我在谷歌浏览器的开发工具中没有错误。 这是我的代码:
$(document).ready(function(){
$(".lbox").click(function(){
$("body").append("<DIV class='lbox_container'><DIV class='img_container'><IMG src='" + this.src + "'/></DIV></DIV>");
$(".lbox_container").width($(document).width()).height($(document).height());
});
$(".lbox_container").click(function(){
$(".lbox_container").remove();
});
});
最佳答案
而不是
$(".lbox_container").click(function(){
$(".lbox_container").remove();
});
使用这个:
$("body").on('click','div.lbox_container', function(){
$(".lbox_container").remove();
});
您需要这样做,因为 jQuery 不会在 DOM 中的新项目上注册 .click() 事件,而只会在调用 document.ready 函数时页面上存在的项目上注册 .click() 事件。
关于javascript - 自定义 Javascript 灯箱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11123788/