简体   繁体   中英

incrementing index in each loop jQuery/javascript

I have a json file that contains paths to many images that I wish to add more image paths to occasionally. I am making a GET request to this file and adding the images to a html page. The issue I am having is using the $.each method is that the index is remaining the same, meaning that each image is repeated in each row, however what I want to do is append 3 different images in each row.

I know I can put [index+1] etc. however this will not scale the more images I have.

I hope this makes sense. If not let me know and I can provide more details.

Please see code below.

HTML

<div class="portrait-page"></div>

JAVASCRIPT

$.get('json/categories.json', function( data ){
    $.each(data, function( index, value ) {
        $('.portrait-page .container').append( "<div class='grid'><div class='col-1-3'><img src='" + data[index].image + "''></div><div class='col-1-3'><img src='" + data[index].image + "''></div><div class='col-1-3'><img src='" + data[index].image + "''></div></div>");
    });
});

JSON file

[
    {"image":"images/geysir.jpg"},
    {"image":"images/burren.jpg"},
    {"image":"images/cuba.jpg"},
    {"image":"images/london.jpg"},
    {"image":"images/vegas.jpg"},
    {"image":"images/cliff.jpg"},
    {"image":"images/timbaland.jpg"},
    {"image":"images/burren.jpg"},
    {"image":"images/che.jpg"}
]

CSS

[class*='col-'] {
    float: left;
}
.col-1-3 {
    width: 33.33%;
}
.grid:after {
    content: "";
    display: table;
    clear: both;
}
*, *:after, *:before {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
[class*='col-'] {
    padding: 5px 5px 0 5px;
}
.col-1-3 img {
    width: 100%;
    height: 300px;
}

You can do something like this:

$.each(data, function( index, value ) {
    if((index + 1) % 3 == 0){
       $('.portrait-page').append( "<img src=" + data[index-2].image + "><img src='" + data[index-1].image + "><img src=" + data[index].image + ">");
    }
});

OR

for(var i = 0; i < data.length - 3; i+=3){
   $('.portrait-page').append( "<img src=" + data[i].image + "><img src='" + data[i+1].image + "><img src=" + data[i+2].image + ">");
}

If you're going to do multiple images per iteration, you don't want $.each , you want your own loop.

You might do something like this:

If you know data.length will be an exact multiple of 3:

$.get('json/categories.json', function( data ){
    var container = $(".portrait-page .container");
    var markup;
    var index = 0;
    while (index < data.length) {
        markup = "<div class='grid'>";
        for (var n = 0; n < 3; ++n) {
            markup += "<div class='col-1-3'><img src='" + data[index++].image + "'></div>";
        }
        markup += "</div>";
        container.append(markup);
    }
});

If you don't, we just throw in an if :

$.get('json/categories.json', function( data ){
    var container = $(".portrait-page .container");
    var markup;
    var img;
    var index = 0;
    while (index < data.length) {
        markup = "<div class='grid'>";
        for (var n = 0; n < 3; ++n) {
            if (index < data.length) {
                img = "<img src='" + data[index++].image + "'>";
            } else {
                img = "";
            }
            markup += "<div class='col-1-3'>" + img + "</div>";
        }
        markup += "</div>";
        container.append(markup);
    }
});

Example:

 var data = JSON.parse( '[' + '{"image":"one"},' + '{"image":"two"},' + '{"image":"three"},' + '{"image":"four"},' + '{"image":"five"},' + '{"image":"six"},' + '{"image":"seven"}' + ']' ); var container = $(".portrait-page .container"); var markup; var img; var index = 0; while (index < data.length) { markup = "<div class='grid'>"; for (var n = 0; n < 3; ++n) { if (index < data.length) { img = "[img src='" + data[index++].image + "']"; } else { img = ""; } markup += "<div class='col-1-3'>" + img + "</div>"; } markup += "</div>"; container.append(markup); } 
 div.col-1-3 { display: inline-block; } 
 <div class="portrait-page"> <div class="container"></div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

Since it seems that you just render all of the images from the json file into the .portrait-page element, Your loop should look like this:

var $container = $('.portrait-page');
$.get('json/categories.json', function( data ){
    $.each(data, function( index, value ) {
        $container.append( "<img src=" + value.image + " />");
    });
});

If for some reason you want to render them in batches of 3, you should do:

var $container = $('.portrait-page');
$.get('json/categories.json', function( data ){
    for(var i = 0; i < data.length - 3; i+=3){
        var $grid = $('<div />').addClass('grid');
        $grid.append( "<img src=" + data[i].image + " />")
             .append( "<img src=" + data[i+1].image + " />")
             .append( "<img src=" + data[i+2].image + " />")
             .appendTo($container);
    });
});

dont use this

$('.portrait-page').append( "<img src=" + data[index].image + "><img src='" + data[index].image + "><img src=" + data[index].image + ">");


well you have to get values using value not data
just give console.log and check whats coming in value.image to get better idea

   $('.portrait-page').append( "<img src=" + value.image + "><img src='" + value.image + "><img src=" + value.image + ">");

There's nothing wrong using $.each at all, the index should increment nicely as well.

Since you need to create DOM anyway, you can do it in the loop, just use the % operator to check for every third item. If it's a 3rd item, add the complete row to the wrapper and create a new DOM object for a new row.

jQuery

var $htmlEl = $('.portrait-page');
var $rowEl = $('<div class="grid"></div>');
$.each(data, function(index, value) {
  $rowEl.append('<div class="col-1-3"><img src="' + value.image + '" /></div>');
  if (((index + 1) % 3) === 0) {
    $htmlEl.append($rowEl);
    $rowEl = $('<div class="grid"></div>');
  }
});

And the complete Fiddle: https://jsfiddle.net/wtg1trjn/1/

This looks like a job for a for loop:

for(var i = 0; i < data.length - 1; i++){
   $('.portrait-page').append( "<img src=" + data[i].image + ">");
}

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.

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