在SO中多次询问这个问题.但我还是得不到东西.
我想从回调中获得一些价值.请查看下面的脚本以获得说明.
function foo(address){
// google map stuff
geocoder.geocode( { 'address': address}, function(results, status) {
results[0].geometry.location; // I want to return this value
})
}
foo(); //result should be results[0].geometry.location; value
Run Code Online (Sandbox Code Playgroud)
如果我试图返回该值只是"未定义".我从SO那里听了一些想法,但仍然失败了.
那些是:
function foo(address){
var returnvalue;
geocoder.geocode( { 'address': address}, function(results, status) {
returnvalue = results[0].geometry.location;
})
return returnvalue;
}
foo(); //still undefined
Run Code Online (Sandbox Code Playgroud) 我正在动态地向<script>页面添加标签<head>,我希望能够以某种方式判断加载是否失败 - 404,加载脚本中的脚本错误等等.
在Firefox中,这有效:
var script_tag = document.createElement('script');
script_tag.setAttribute('type', 'text/javascript');
script_tag.setAttribute('src', 'http://fail.org/nonexistant.js');
script_tag.onerror = function() { alert("Loading failed!"); }
document.getElementsByTagName('head')[0].appendChild(script_tag);
Run Code Online (Sandbox Code Playgroud)
但是,这在IE或Safari中不起作用.
有没有人知道如何在Firefox以外的浏览器中使用它?
(我不认为需要在.js文件中放置特殊代码的解决方案是一个很好的解决方案.它不够优雅且不灵活.)