簡體   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