我有一个回调函数
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
被多次重新分配给不同的东西。
您可以做一些选择。
- 使用您需要的参数调用您的回调
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);
});
- 将变量保存在闭包中
(function() {
var value = j;
...
})();
- 使用
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);
});
})
});
- 如果你使用 es6,你可以使用
let
关键字。 Here是一些很好的解释,它在使用 for 循环时是如何工作的
for(let i = 0; i < 10; i++) {
console.log(i);
setTimeout(function() {
console.log('The number is ' + i);
},1000);
}
关于javascript - 在回调函数中获取变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50470721/