如何从foo获得响应.Onload = function(){
How to get response from foo.onload = function(){?
我有一个使用.onload触发的函数。我想返回一个值:
newImg.onload = function() {
var height = newImg.height;
var width = newImg.width;
if(height > width){
console.log(false);
return false;
} else {
console.log(true);
return true;
}
}
newImg.src = imgSrc; // this must be done AFTER setting onload
通常我会这样写
var foo = function(){...
但是在这种情况下不起作用。我该怎么办呢?
异步调用不能返回值。您需要像在Ajax请求中那样使用回调。
function loadImg (imgSrc, callback) {
var newImg = new Image();
newImg.onload = function() {
var height = newImg.height;
var width = newImg.width;
if(height > width){
console.log(false)
if(callback) callback(false);
} else {
console.log(true)
if(callback) callback(true);
}
};
newImg.onerror = function () {
if(callback) callback('error');
};
newImg.src = imgSrc;
}
loadImg("foo.gif", function(status) { console.log("Do Next Step"); })
您有两个选择;
-
将值设置为其他变量
var foo; newImg.onload = function () { foo = true; }; // Sometime later read `foo`.
…尽管这很容易导致灾难,因为您不能保证何时设置变量,因为图像将花费一些时间来加载。
-
一个更好的选择是调用另一个函数,传递你想传递的值,然后相应地处理它。
newImg.onload = function () { foo(true); }; function foo(result) { // do something with result }
相关文章:
- 直接在函数声明上使用function.prototype.bind
- jQuery:.click(function(){(element),collapse('show',f
- window.onload没有'无法在Android WebView中工作
- JavaScript-动态SVG-onload属性-未触发事件
- 如果连接类型为none,则Javascript Function Only警报
- 在phonegap中为android调用onload函数的最佳方式
- onLoad function phonegap android
- 在 meteor js 中为 window.onload(function(){}) 和 $(document).rea
- 如何在 jQuery 中的 img.onload = function() 中返回一个变量
- window.onload = function(){ . } / window.onload = function()
- Mixing window.onload and jQuery $(function(){})
- window.onload = function(){};限制为包含一定数量的行
- Javascript unonload and onload function
- fadeIn onLoad function
- 虽然身体.Onload为false = function
- 如何从foo获得响应.Onload = function(){
- jQuery .change function onload
- Ajax function onload
- onload function js
- if (condition), then body onLoad javascript function