如何在Fancybox 2中为打开的图像添加html数据属性?

时间:2014-07-11 15:34:29

标签: javascript jquery fancybox fancybox-2

我希望打开的图片具有属性data-pin="true"

以下是我希望打开的图片的html看起来像:

<img data-pin="true" class="fancybox-image" src="/uploads/gallery_item/image/426/full_ExShow2013_3156.jpg#lightbox0" alt="" >

这是我没有工作的JS:

$('.fancybox').fancybox({
    beforeLoad: function(){
      $(this.element).data("pin", "true")
    }
});

修改

缩略图的HTML:

<a class="fancybox" href="/uploads/gallery_item/image/426/full_example.jpg" rel="gallery">
          <img alt="" data-src="/uploads/gallery_item/image/426/example.jpg" src="/uploads/gallery_item/image/426/example.jpg" style="width: 301px; height: 301px;"></div>
</a>

2 个答案:

答案 0 :(得分:1)

仅仅因为您的img没有XML属性并不意味着它没有数据。

通常

$(something).data("key", value);

不会将实际的data-key属性添加到XML元素中,但它们将存储在DOM元素本身中。

如果您想明确添加标记属性,则需要通过$.attr

执行此操作
$(something).attr("data-key", value);

答案 1 :(得分:1)

您应该定位打开图像的选择器,如:

$(".fancybox").fancybox({
    beforeShow: function () {
        $(".fancybox-image").attr("data-pin", true)
    }
});

参见 JSFIDDLE

注意:请记住,当您使用$(this.element)时,实际上是指引发fancybox而不是open元素本身的链接。