繁体   English   中英

在回调函数中获取变量值

[英]get variable value in callback function

我有一个回调函数

function QueryKeyword(keyword, site, callback) {
  var querykeyword = keyword;
  var website = site;

  $.ajax({
    url: "http://www.test.com",
    jsonp: "jsonp",
    dataType: "jsonp",
    data: {
      Query: querykeyword
    },
    success: callback
  });
}

我在这样的for循环中调用此函数:

for (i = 0; i < questionTerm.length; i++) {
  for (j = 0; j < site.length; j++) {
    var searchTerm = questionTerm[i] + ' ' + $('#search').val();

    QueryKeyword(searchTerm, site[j], function(reslt) {
      // I need to get j variable value here
      console.log(j);
    });

  }

}

现在,我需要在函数中获取“ j”变量值,请参阅控制台j变量值,但它无法获取j变量值。

您能否让我知道我如何获取这一价值。

提前致谢

问题是,在回调时, j被多次重新分配给其他内容。

您可以选择几种方法。

  1. 使用所需的参数调用回调

 function QueryKeyword(keyword, site, index, callback) { // ... $.ajax( success: function(result) { // call the callback with a second param (the index j) callback(result, index); } ) } QueryKeyword(searchTerm, site[j], j, function(reslt, param) { // param is j console.log(result, param); }); 

  1. 将var保存在一个闭包中

 (function() { var value = j; ... })(); 

  1. 用于forEach

 questionTerm.forEach((term, i) => { site.forEach((s, j) => { // we are in a closure, // j will be correct here. QueryKeyword(term, s, function(reslt) { // j is still correct here console.log(j); }); }) }); 

  1. 如果使用es6,则可以使用let关键字。 是一些很好的解释,它在使用for循环时如何工作

 for(let i = 0; i < 10; i++) { console.log(i); setTimeout(function() { console.log('The number is ' + i); },1000); } 

您必须分别传递:

定义

function QueryKeyword(keyword, site, index, callback)
{
   ...
}

执行

QueryKeyword(searchTerm, site[j], j, function(reslt) {
   // I need to get j variable value here
   console.log(j);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM