0

I have an ajax which loads a few buttons based on some json data

$.ajax({
    type: "GET",
    url: "/some/",
    dataType: 'json',
    success: function(data) {
        for(var i = 0; i < data.cities.length; i++)
        {
            var button = document.createElement("button");
            var a = data.cities[i].a;
            var b = data.cities[i].b;
            button.onclick = function() { alert(a + ', ' + b); };
            button.innerHTML = a + ', ' + b;
            $("#div").append(button);
        }
    }
});

Each record in json is different what is shown on loaded buttons but when I click on any of them alert is shown with data from last record. As I understand each step of loop overwrites onclick functions for all buttons that have been already created but I can't figure out why and how to fix it. Does anyone know maybe what is the problem here?

kebie
  • 485
  • 5
  • 16

0 Answers0