vendredi 8 juillet 2016

jQuery .each method returning last value

I feel like the .each() method isn't really working. Here is my code:

function makeHTML(data) {
console.info(data.categories);

$(data).each(function () {
    let createButton = `
                <div class="col-md-6">
                    <button type="button" class="btn btn-default">
                        <a href="${data.categories.category.id}" 
                        target="_blank">${data.categories.category.title}</a>
                    </button>
                </div>
                `;
    document.getElementById('table').innerHTML = createButton;
});
}

$(document).ready(function () {
$.ajax({
    type: 'GET',
    contentType: "application/json; charset=utf-8",
    url: "json/data.json",
    dataType: "json",
    success: makeHTML,
    error: function (result) {
        console.error(result);
    }
});
});

It's only returning the last set in the json which looks like this:

{
  "categories": {
    "category": {
      "title": "Something",
      "id": 1
    },
    "category": {
      "title": "Something Else",
      "id": 2
    }
  }
}

I tried adding debugger; immediately after the innerHTML = createButton; to watch the loop, but it goes into jQuery just once. It's weird. I don't know what I am doing wrong?

Aucun commentaire:

Enregistrer un commentaire