我在页面上有多个元素,其中包含data-attribute
data-lightbox="image"
HTML看起来像
<div class="image isotope-item" id="image_72">
<div class="work-item">
<div class="dima-masonry-100"></div>
<img src="/path/to/img" alt="Valley" />
<div class="link_overlay">
<ul class="icons-media">
<li>
<a data-lightbox="image" href="/path/to/img">
<i class="fa fa-link"></i>
</a>
</li>
<li>
<a href="/images/72"><i class='fa fa-credit-card'></i></a>
</li>
</ul>
<div class="work-info">
<div class="work-title text-center">
<p>Random Valley 3</p>
</div>
</div>
<span class="topaz-hover"></span>
</div>
</div>
</div>
<div class="image isotope-item ok-md-3 ok-xsd-6 ok-sd-6 PlacesOfInterest" id="image_71">
<div class="work-item">
<div class="dima-masonry-100"></div>
<img src="/path/to/img" alt="Usk" />
<div class="link_overlay">
<ul class="icons-media">
<li>
<a data-lightbox="image" href="/path/to/img">
<i class="fa fa-link"></i>
</a>
</li>
<li>
<a href="/images/71"><i class='fa fa-credit-card'></i></a>
</li>
</ul>
<div class="work-info">
<div class="work-title text-center">
<p>Usk Valley 3</p>
</div>
</div>
<span class="topaz-hover"></span>
</div>
</div>
</div>
所以为了让大胆的弹出窗口工作,我可以做到
// Portfolio Lightbox
$(function(){
if($('body').hasClass('pages portfolio')){
e.preventDefault();
var i = $('[data-lightbox="image"]');
i.magnificPopup({
type: 'image',
closeOnContentClick: !0,
closeBtnInside: !1,
fixedContentPos: !0,
mainClass: "mfp-zoom-in",
image: {
verticalFit: !0
}
});
}
});
但我也通过AJAX调用加载额外的图像,因此需要使用事件委托来动态创建元素
所以我已将代码更改为
// Portfolio Lightbox
$(function(){
if($('body').hasClass('pages portfolio')){
$(document).on('click', function(e) {
e.preventDefault();
var d = $('[data-lightbox="image"]');
d.magnificPopup({
type: 'image',
closeOnContentClick: !0,
closeBtnInside: !1,
fixedContentPos: !0,
mainClass: "mfp-zoom-in",
image: {
verticalFit: !0
}
});
});
}
});
我发现有时我必须点击两次链接才能触发事件。也可以使用
var d = $('[data-lightbox="image"]');
我在页面上选择所有这些元素,当我认为我应该做的是利用$(this)
但似乎无法使其正常工作
记录对象
var d = $('[data-lightbox="image"]');
console.log(d);
[a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, prevObject: jQuery.fn.init[1], context: document, selector: "[data-lightbox="image"]"]
var d = $(this);
console.log(d);
[document, context: document]