for (a = 1; a <= 2; a++) {

  $("#inp-" + a + "  .nama").autocomplete({
    source: function(request, response) {
      $.ajax({
        url: "states_remote.php",
        dataType: "json",
        data: {
          term: request.term
        },
        success: function(data) {
          response($.map(data, function(item) {
            return {
              value: item.nama,
              pangkat: item.pangkat,
              jabatan: item.jabatan,
              nip: item.nip
            };
          }));
        }
      });
    },
    minLength: 2,
    select: function(event, ui) {
      $("#inp-" + a + " .pangkat").val(ui.item.pangkat);
      $("#inp-" + a + " .nip").val(ui.item.nip);
      $("#inp-" + a + " .jabatan").val(ui.item.jabatan);

      $(this).next('.nama').focus();
    },
    html: true,
    open: function(event, ui) {
      $(".ui-autocomplete").css("z-index", 1000);
    }
  });
}


我想在自动组合选择功能中使用循环变量a,但是我无法访问此函数中的调用变量

select: function(event, ui) {
  $("#inp-" + a + " .pangkat").val(ui.item.pangkat);
  $("#inp-" + a + " .nip").val(ui.item.nip);
  $("#inp-" + a + " .jabatan").val(ui.item.jabatan);

  $(this).next('.nama').focus();
},


有人可以帮助我解决我的问题吗?我在其他主题中搜索,也许这个名字是异步函数。

最佳答案

尝试使用闭包:-



for (a = 1; a <= 2; a++) {

  (function(a) {

    $("#inp-" + a + "  .nama").autocomplete({
      source: function(request, response) {
        $.ajax({
          url: "states_remote.php",
          dataType: "json",
          data: {
            term: request.term
          },
          success: function(data) {
            response($.map(data, function(item) {
              return {
                value: item.nama,
                pangkat: item.pangkat,
                jabatan: item.jabatan,
                nip: item.nip
              };
            }));
          }
        });
      },
      minLength: 2,
      select: function(event, ui) {
        $("#inp-" + a + " .pangkat").val(ui.item.pangkat);
        $("#inp-" + a + " .nip").val(ui.item.nip);
        $("#inp-" + a + " .jabatan").val(ui.item.jabatan);

        $(this).next('.nama').focus();
      },
      html: true,
      open: function(event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);
      }
    });

  })(a);

}

10-08 03:09