我一直在使用this代码来获取在我的网站上工作的简单灯箱。
我尝试稍微修改它:
a)灯箱淡入 - 完成
b)脚本提取的src
属性不是href
- 完成
b)我可以将<img>
上的自定义“数据描述”属性中的数据提取到灯箱中的<p>
点击(或我点击)。
问题
对于第二个,当第一次点击图像时,它工作正常。当点击任何其他人,或者再次点击它时,没有任何反应 - 我无法理解为什么我似乎做得对吗?
此外,当使用jQuery 1.9时,live()
显然已被折旧 - 我之前使用过1.8.2并且直到现在才注意到,我已经尝试了on()
没有成功,并且是一个JS初学者对如何修复它感到困惑,这个问题意味着灯箱不会关闭。
几乎工作但破损的代码:http://codepen.io/hwg/pen/ybEAw - 对所有评论感到抱歉,但我觉得这样更容易。
JS:
$(document).ready(function() { //Document Ready
$('.inner_img').click(function(e) {
//prevent default action (hyperlink)
e.preventDefault();
//Get clicked link href
var image_src = $(this).attr("src");
// Get Description
var desc = $(this).attr("data-description");
/*
If the lightbox window HTML already exists in document,
change the img src to to match the href of whatever link was clicked
If the lightbox window HTML doesn't exists, create it and insert it.
(This will only happen the first time around)
*/
if ($('#lightbox').length > 0) { // #lightbox exists
//place href as img src value
$('#content').html('<img src="' + image_src + '" />');
// Change Description in the P tag
$('.desc').html(' '+ desc +' ');
//show lightbox window - you could use .show('fast') for a transition
$('#lightbox').fadeIn(); // Fades it in
}
else { //#lightbox does not exist - create and insert (runs 1st time only)
//create HTML markup for lightbox window
var lightbox =
'<div id="lightbox">' +
'<p>Click to close</p>' +
'<div id="content">' + //insert clicked link's href into img src
'<img src="' + image_src +'" />' +
'<p class="desc">'+ desc +'</p>' + // Adds Description from <img data-description="..">
'</div>' +
'</div>';
//insert lightbox HTML into page
$(lightbox).hide().appendTo("body").fadeIn();
}
});
//Click anywhere on the page to get rid of lightbox window
$('#lightbox').on('click', function() { //must use live, as the lightbox element is inserted into the DOM
$("#lightbox").fadeOut(); // Fades it out
});
}); // End
感谢您的帮助。
编辑:我发现live
/ on
问题很常见,我可以看到我哪里出错了。感谢您对此评论者的帮助。
但是,为什么我的代码不适用于第二个问题?
答案 0 :(得分:2)
在on -
上使用事件委托$(document.body).on('click','#lightbox', function() {
$("#lightbox").fadeOut(); // Fades it out
});
答案 1 :(得分:0)
您可以更改
$('.inner_img').click(function(e) {
到
$(document.body).on('click', '.inner_img', function(e) {
以便绑定后发生的事件仍然会委托给新元素。