【问题标题】:Problema usin fancybox with new images added through jQuery Append使用通过 jQuery Append 添加的新图像的问题
【发布时间】:2012-03-29 10:34:02
【问题描述】:

我正在向这个 DIV 的 DOM 添加新图像...

<div id="photoArea"></div>

然后我像这样加载新图像...

function showImages(token,status){
var jqxhr = $.getJSON("/api/1/photos/show.json/?callback=?",{ 
    token: token,
    status_id: status,
},function(data) {
    var html = "";
$.each(data.photos, function(i,photo){
    html = '<a class="fancybox" rel="gallery1" href="/photos/'+photo.owner_id+'/'+photo.id+'-'+photo.photo_token+'.'+photo.extension+'">';
    html += '<img src="/photos/'+photo.owner_id+'/'+photo.id+'-'+photo.photo_token+'x200.'+photo.extension+'" alt="" /> ';
    html += '</a>';
    $('#photoArea').append(html);
});
}).success(function(data) { });
} // end function

我尝试了很多组合。其中之一是:

$(document).on("click",".fancybox",function(ev){
 $.fancybox({
    href: this,
    type: 'image'
 });
});

当我点击图像时,导航器中只显示图像。

我正在使用 jQuery 1.7 和 fancybox v2。 Las Chrome 和 Firefox 版本

关于如何将fancybox中的新图像显示到这些新图像的任何想法我

【问题讨论】:

    标签: jquery fancybox


    【解决方案1】:

    “on”函数通常用于 DOM 的现有项目。 如果要考虑通过 ajax 检索的项目,最好使用 .delegate()。像

    $("#photoArea").delegate("img.fancybox", "click", function() {
        ...
    });
    

    如果您已经在 getJSON 函数中实现了一个空的成功函数,那么还有什么意义呢?您可能应该删除它并使用 Firebug 或 Chrome Inspector 验证您的数据实际上已添加到 DOM。

    希望有所帮助:)

    【讨论】:

    • "on" 函数通常用于 DOM 的现有项 - 这不一定是真的,因为自 jQuery v1.7 以来.on() 实际上已经取代了.live() 。X。对于旧版本,建议使用 .delegate() 而不是 .live()
    【解决方案2】:

    使用 fancybox v2.x,您只需要这个自定义脚本

    $(document).ready(function(){
     $(".fancybox").fancybox({
      // options if needed
     }); // fancybox
    }); // ready
    

    fancybox v2.x 支持现有元素和动态添加的元素,因此您不需要.on().delegate()。只需确保 jQuery、fancybox js 文件和您的自定义脚本在您添加图像的容器之前加载。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-04
      • 1970-01-01
      • 1970-01-01
      • 2014-09-19
      • 1970-01-01
      • 2011-07-03
      • 2013-12-02
      相关资源
      最近更新 更多