【发布时间】:2010-07-30 20:10:40
【问题描述】:
我正在尝试理解 JS 中的 JSON、回调等。从下面更改的示例中,您将看到我在 $.getJSON 的函数回调中。然后,我跳入 getSomething() 并期望它改变我的结果变量。它会在函数范围内改变它,但当我跳出该函数时不会。
您会从 2 个 console.log() 中看到,第一个显示正确,而第二个显示不正确。我确定我的问题的答案与通过返回变量有关。回调,但有人可以启发
我 :)
谢谢!
代码:
$.getJSON('/cart.js', function (cart, textStatus) {
var result = '';
result += 'Sample Stuff';
StackOverflow.getSomething(param1, param2, function(a, b) {
for(j=0; j < b.length; j++) {
if (b.options[j] != 'Default Title') {
if (a.options[j].name.indexOf("Color") > -1) {
result += b.options[j].name;
console.log(result); // <-- It comes out correct (Sample Stuff + b.options...)
}
}
}
});
console.log(result); // <-- It comes out incorrect, just (Sample Stuff)
});
【问题讨论】:
标签: javascript jquery json return-value