lundi 2 novembre 2015

For loop if statement confusion

I have a JavaScript object literal array that I'm trying to create a simple for loop to pull in all the info. The problem is that I'm trying to use an If statement to close and reopen divs when there are more than 4 books in a row. But when there are more than 4 books it adds these divs to every instance of the book object, creating a row for every item. I just can't for the life of me think what the correct condition is that will only close an reopen the divs every 4 books.

    var bookInfo = '';
    var book;


   function print(bookInfo) {
     var outputDiv = document.getElementById('books-go-here');
     outputDiv.innerHTML = bookInfo;
   }

    for(var i = 0; i < books.length; i += 1){
     book = books[i];
     bookInfo += '<div class="large-3 small-6 columns output">';
     bookInfo += '<img src="' + book.image + '"/>';
     bookInfo += '<div class="panel">';
     bookInfo += '<h2>' + book.name + '</h2>';
     bookInfo += '<p>' + book.description + '</p>';
     bookInfo += '</div>';
     bookInfo += '</div>';
     // return bookInfo;
      if (books.length > 4) {
         bookInfo += '</div>"';
         bookInfo += '</div>"';
         bookInfo += '</div>"';
         bookInfo += '<div class="row">';
         bookInfo += '<div class="large-12 columns">';
         bookInfo += '<div id="books-go-here" class="row">';
       }

     }
   print(bookInfo);

Any help is greatly appreciated as this is truly pickling my brain at the moment.

Aucun commentaire:

Enregistrer un commentaire