2014-02-11 68 views
0

我在这里发布了一段代码,我得到一个运行时错误。变量x变化是价值Ajax调用内:JQuery变化的变量

$("#acquisto").click(function(){ 
      var x = 0; 
      for(x = 0; x < numRighe; x++){ 
       if($("#ch"+x).prop("checked") == true){ 
        alert("#tr"+x); 
        $.ajax({ 
          url:"eliminazioneRecord.php", 
          type: "GET", 
          data: { Codice: $("#ch"+x).val() }, 
          success:function(result){ 
          //$("#tr"+x).fadeOut("slow"); 
          alert("#tr"+x); 
         }, 
          error:function(richiesta,stato,errori){ 
          alert("<strong>Chiamata fallita:</strong>"+stato+" "+errori); 
         } 
        }); 
       } 
      } 
     }); 

我意识到,因为在Ajax调用x前的警报具有的值是不同的成功函数内部的警报显示一个。我错在哪里?

回答

0

这是因为您正在循环中使用循环变量x

$("#acquisto").click(function() { 
    for (var x = 0; x < numRighe; x++) { 
     (function (x) { 
      if ($("#ch" + x).prop("checked") == true) { 
       alert("#tr" + x); 
       $.ajax({ 
        url: "eliminazioneRecord.php", 
        type: "GET", 
        data: { 
         Codice: $("#ch" + x).val() 
        }, 
        success: function (result) { 
         //$("#tr"+x).fadeOut("slow"); 
         alert("#tr" + x); 
        }, 
        error: function (richiesta, stato, errori) { 
         alert("<strong>Chiamata fallita:</strong>" + stato + " " + errori); 
        } 
       }); 
      } 
     })(x) 
    } 
}); 

阅读:

1

所有匿名函数传递给success$.ajax参照从由所述用于递增外部范围相同x可变结构体。你需要每个功能都有自己的副本x

success:function(copy_x) { 
    return function(result){ 
    //$("#tr"+copy_x).fadeOut("slow"); 
    alert("#tr"+copy_x); 
    } 
}(x),