运行get_style_guide_version()
控制台时,将返回预期的数据,但在浏览器中显示的是undefined
。这是为什么?
function get_style_guide_version() {
var jqxhr = $.getJSON( '/package.json', function() {
})
.done(function(data) {
output = data.version;
console.log(output);
return output;
});
}
$( document ).ready(function() {
document.write(get_style_guide_version());
});
在准备文档的函数上,您尝试编写get_style_guide_version()的结果,该结果正在运行异步进程
因此该函数在异步返回之前完成,因此无法正常工作。
您应该做的是拥有另一个手动调用的函数,该函数会写入文档,并在.done promise触发时被调用。
function get_style_guide_version() {
var jqxhr = $.getJSON( '/package.json', function() {
})
.done(function(data) {
output = data.version;
console.log(output);
write(output);
});
}
$( document ).ready(function() {
document.write(get_style_guide_version());
});
function write(val){
document.write(val);
}
或者
function get_style_guide_version(done) {
var jqxhr = $.getJSON( '/package.json', function() {
})
.done(function(data) {
output = data.version;
console.log(output);
done(output);
});
}
$( document ).ready(function() {
document.write(get_style_guide_version(function(val){
document.write(val);
}));
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句