Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

javascript - Why always the last reference to the object is used in loop?

The assemblyEl is created correctly(1.jpg, 2.jpg, 3.jpg), but the ajax request always sends the last id(3).

Why this happens and how to fix it?

var assemblies = [{id:1},{id:2},{id:3}];

for (var a in assemblies) {
    var assembly = assemblies[a];

    var assemblyEl = $('<img src="' + assembly.id + '.jpg" />')
                        .click(function () {
                                 $.ajax({
                                     type: "POST",
                                     url: url,
                                     data: { id: assembly.id },
                                     async: false,
                                     success: function (data) {
                                     }
                                 });
                         });
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because the click event fires when the element is clicked. By the time that happens, the value of assembly is the last value in the loop.

Use a closure to copy the value to the new scope.

function clickHandler(assembly) {
    return function () {
         $.ajax({
              type: "POST",
              url: url,
              data: { id: assembly.id },
              async: false,
              success: function (data) {
              }
          });
    };
}

.click(clickHandler(assembly));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...