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

后端 未结 1 784
南笙
南笙 2020-12-07 05:07

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?

相关标签:
1条回答
  • 2020-12-07 05:41

    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));
    
    0 讨论(0)
提交回复
热议问题