本文介绍了通过Ajax返回的Colorbox和内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jquery colorbox在窗口中弹出用户帐户.我也有一个按钮,可以通过ajax将更多的用户加载到页面中,但是由于某些原因,加载了ajax的用户不会在colorbox窗口中弹出.如何使Colorbox处理通过Ajax返回的内容?

I'm using jquery colorbox to popup user accounts in a window. I also have a button that loads more users into the page via ajax, but for some reason users loaded with ajax do not popup in colorbox window. How can I get colorbox to work with the content that was returned via ajax?

function loadMore(pageNo) {
    //$("#loading").html('Loading...').show();
    var url = '/search/resultsAjax';
    $.get(url, {page: pageNo}, function(response) {
        $("#results").append(response);
        //$("#loading").hide();
    });
}

$(document).ready(function() {
    var currPage = 1;
    $("a.next").click(function() {
        loadMore(++currPage);
    });

    $("a.usr").colorbox({width:"960px", height:"90%", iframe:true});
});

推荐答案

当您将$(document).ready()中的colorbox与此绑定时:

When you bind colorbox in $(document).ready() with this:

$("a.usr").colorbox({width:"960px", height:"90%", iframe:true});

jQuery将搜索整个页面,获取与a.usr匹配的所有内容,将colorbox绑定到这些项目,然后忘记有关a.usr的所有内容. jQuery不会记住您对a.usr感兴趣,因此不会对新内容进行色箱包装.

jQuery will go search through the page, grab everything that matches a.usr, bind colorbox to those items, and then forget all about a.usr. jQuery won't remember that you're interested in a.usr so the new ones won't be colorbox'd.

对于这种情况,通常的解决方案是使用.live().delegate(),但是由于没有"colorbox"事件,因此它们在这里不起作用.

The usual solution to this sort of thing is to use .live() or .delegate() but those won't work here as there isn't a "colorbox" event.

但是,您可以轻松地手动绑定colorbox.尝试将loadMore更改为类似以下内容:

However, you can bind colorbox by hand easily enough. Try change loadMore to something more like this:

function loadMore(pageNo) {
    $.get('/search/resultsAjax', { page: pageNo }, function(response) {
        var $html = $(response);
        $html.find('a.usr').colorbox({ width: '960px', height: '90%', iframe: true });
        $('#results').append($html);
    };
}

您只需将response HTML转换为jQuery对象,找到其中的所有a.usr内容,将colorbox绑定到这些内容,然后像往常一样将新的HTML插入DOM.

You just turn the response HTML into a jQuery object, find all the a.usr things inside it, bind colorbox to those, and then insert the new HTML into the DOM as usual.

这篇关于通过Ajax返回的Colorbox和内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 21:54