Masonry:在AJAX回调上创建一个网格

Masonry: Creating a grid on AJAX callback

本文关键字:一个 网格 创建 AJAX 回调 Masonry      更新时间:2023-09-27

所以我对Masonry很熟悉,但我以前从未这样做过。

我知道在通过ajax加载页面后向网格添加项目的"added"方法,但这并不是我想要做的

我的网格结构在通过ajax调用之前根本不存在。

例如(伪代码):

  1. 页面加载
  2. 用户单击链接
  3. AJAX调用,返回HTML字符串并通过jQuery添加到dom中
  4. 需要实例化基于此HTML的砖石网格

基本上,通过AJAX返回的HTML看起来像这样:

<div class="grid-57">
    <a class="item" href="http://www.example.com">
        <img src="http://fpoimg.com/350x350"/></a> 
    </a>
    <a class="item" href="http://www.example.com">
        <img src="http://fpoimg.com/350x250"/></a> 
    </a>
    <a class="item" href="http://www.example.com">
        <img src="http://fpoimg.com/350x450"/></a> 
    </a>
</div>

所以,正如您所看到的,我并没有添加到现有的网格或砖石结构中,我需要在AJAX成功返回时创建一个新的网格或砌体。

我的JS看起来像这样:

$('.get-grid').click(function(e){
    var id = $(this).data('id');
    $.post(ajaxurl, { action: 'get_grid', id: id  }, function(response) {
        // Append this html to the area of the site where I have the grids. 
        $('.all-the-grids').append(response);
        // Here is where i need to actually turn this HTML that I just added into a masonry object and lay it out.
        var $container = $('.grid-' + id);
        msnry = new Masonry( $container[0], {
            columnWidth: 188,
            itemSelector: '.item',
            gutter: 10
        }); 
        msnry.on('layoutComplete', function(){
            // never making it in here.
        }); 
    });
});

知道怎么做吗?

编辑

看起来我的网格布局正确,没有错误,但它从未到达这里的layoutComplete回调。

以与通常使用Masonry相同的方式进行操作,在回调中进行操作并不会真正改变任何事情。

$('.get-grid').click(function(e){
    var id = $(this).data('id');
    $.post(ajaxurl, { action: 'get_grid', id: id  }, function(response) {
        // Append this html to the area of the site where I have the grids. 
        var grids = $('.all-the-grids');
        grids.append(response);
        var msnry = new Masonry(grids[0], {
        });
    });
});

当您在Layout中使用Images时,首先要做的就是等待所有图像加载到该元素中,然后实例化。尝试以下代码

$containers = $('.all-the-grids');
$containers.append(response).imagesLoaded(function() { 
   $containers.masonry({
      itemSelector: '. a'
   }); 
});

注意:imagesLoaded是一个jQuery插件