简体   繁体   English

添加元素以分页每X个div

[英]Adding element to page every X number of divs

I need to run this function every X number of posts and the page uses AJAX to load in new posts as you scroll down the page. 我需要每X个帖子运行此函数,并且当您向下滚动页面时,页面使用AJAX加载新帖子。 I was hoping to use the function below using a for loop with the modulus operator but it doesn't seem to accomplish what i'm looking for. 我希望使用下面的函数使用带有模数运算符的for循环,但它似乎没有完成我正在寻找的东西。 Any idea how to do this? 知道怎么做吗?

$(document).ready(function($) {
function adTileLoop(){
        var adTile = "<div class='new-box' id='article-tile'></div>";
        var adLoc = 11;
        var p = $('#article-tile');
        var tile = $('#article-tile:nth-child('+adLoc+')');
        for(var i = 0; i <= p.length; i++){
                        if(i % adLoc == 0){
                            $(tile).after(adTile);
                        }
        }
}
$('#content').live(adTileLoop);
}

First of all, you need to be careful to keep IDs unique. 首先,您需要小心保持ID唯一。 The fact that you have $("#article-tile") and you are trying to select more than one is a mistake. 您有$("#article-tile")并且您尝试选择多个这一事实是错误的。 ID's must be unique. ID必须是唯一的。

Here's a better way to run over a bunch of divs with jQuery: 这是使用jQuery运行一堆div的更好方法:

$("div").each(function() {
    console.log($(this));
});

You can then improve the selector to select only nth-children as you do in your question: 然后,您可以像在问题中一样改进选择器以仅选择nth-children

$("div:nth-child(2)") for example will get every other div on the page. $("div:nth-child(2)")例如将获取页面上的每个其他div。

To retrieve the information about your posts specifically, use a selector specific to each post, something like: $(".post:nth-child(2)") . 要专门检索有关帖子的信息,请使用特定于每个帖子的选择器,例如: $(".post:nth-child(2)")

As Ashirvad suggested in the comments, you can run this after a successful ajax call and you will be able to retrieve the updated information about your page. 正如Ashirvad在评论中建议的那样,您可以在成功进行ajax调用后运行此功能,并且您将能够检索有关您页面的更新信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM