[英]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
被多次重新分配给其他内容。
您可以选择几种方法。
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); }); }) });
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.