为什么总是在循环中使用对象的最后一个引用? [英] Why always the last reference to the object is used in loop?

查看:119
本文介绍了为什么总是在循环中使用对象的最后一个引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

assemblyEl 是正确创建的(1.jpg,2.jpg,3.jpg),但是ajax请求总是发送最后一个id(3)。

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) {
                                     }
                                 });
                         });
}


推荐答案

因为点击事件会在单击该元素。到那时, assembly 的值是循环中的最后一个值。

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));

这篇关于为什么总是在循环中使用对象的最后一个引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆