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. 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. 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. The fact that you have $("#article-tile")
and you are trying to select more than one is a mistake. ID's must be unique.
Here's a better way to run over a bunch of divs with jQuery:
$("div").each(function() {
console.log($(this));
});
You can then improve the selector to select only nth-children
as you do in your question:
$("div:nth-child(2)")
for example will get every other div on the page.
To retrieve the information about your posts specifically, use a selector specific to each post, something like: $(".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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.