在jquery获取请求中从for循环调用var i

时间:2013-08-26 03:28:26

标签: javascript jquery

我在$ .get的范围内访问var i时遇到问题。这是我的代码:

for (var i = 0; i < printer_ids.length; i++) {
  $.get('/get_printer_status_message/'+printer_ids[i]+'/', function(data) {
    $('#printer_status_'+printer_ids[i]).html(data);

    console.log(data)
    console.log('id: #printer_status_'+printer_ids[i]);
    console.log('current:' + $('#printer_status_'+printer_ids[i]).html());
  });
}

i在$ .get行中定义,但不在$ .get的范围内定义。如何在$ .get的范围内访问var i?

2 个答案:

答案 0 :(得分:1)

更好的重构,避免重新定义每一圈的功能:

var doIt = function (printer_id){
    $.get('/get_printer_status_message/'+printer_id]+'/', function(data) {
      $('#printer_status_'+printer_id).html(data);

      console.log(data)
      console.log('id: #printer_status_'+printer_id);
      console.log('current:' + $('#printer_status_'+printer_id).html());
    });
};

for (var i = 0; i < printer_ids.length; i++) {
    doIt(printer_ids[i]);
}

答案 1 :(得分:0)

您必须在本地范围内捕获i变量:

for (var i = 0; i < printer_ids.length; i++) {
  (function (i){
    $.get('/get_printer_status_message/'+printer_ids[i]+'/', function(data) {
      $('#printer_status_'+printer_ids[i]).html(data);

      console.log(data)
      console.log('id: #printer_status_'+printer_ids[i]);
      console.log('current:' + $('#printer_status_'+printer_ids[i]).html());
    });
  }(i));
}