[英]Setting a global variable from within a nested private function
您好,并预先感谢您对这个难题的帮助!
我在$.imgpreload()
函数中设置globalMaxW
遇到麻烦。
console.log(globalMaxW);
返回0
时,之后称为$.imgpreload()
函数而,所述的内部调用时$.imgpreload()
函数返回正确的图像宽度。
如何从该嵌套函数中设置全局变量globalMaxW
?
谢谢!
var globalMaxW = 0;
function infoWidth() {
$('.swipe-wrap img').each(function(){
var $me = $(this),
mysrc = $me.attr('src');
var newimg = new Image();
newimg.src = mysrc;
$.imgpreload($me, function(){
if(newimg.width > globalMaxW) {
globalMaxW = newimg.width;
}
});
console.log(globalMaxW);
});
$('#info p').css({'width' : globalMaxW});
}
您的console.log(globalMaxW)在以下代码完成执行之前发生,是的,它那时等于零:
$.imgpreload($me, function(){
if(newimg.width > globalMaxW) {
globalMaxW = newimg.width;
}
});
由于该函数是异步的,因此它将开始运行“ imgpreload”,并立即继续运行而无需等待其完成。 将设置globalMaxW,但在console.log()之后...
我假设这是jquery.imgpreload插件。 imgpreload是异步的,因此将设置globalMaxW,但仅在调用第二个参数作为参数传递的回调函数之后才发生,并且仅在以异步方式获取图像之后才发生。 我了解您仅在预加载所有图像后才想设置css属性。 因此,您可以使用jquery延迟对象的集合来完成此任务。
在下面的代码中,将创建jQuery $ .Deferred对象,并将其推送到每个imgpreload调用的数组中。 您可以看到,一旦imgpreload调用了回调,则可以解决deferred问题。
在底部$ .when函数基本上会调用每个$。的调用,完成了promises集合中被延迟的$的解析。
function infoWidth() {
var promises = [];
$('.swipe-wrap img').each(function(){
var $me = $(this),
mysrc = $me.attr('src');
var newimg = new Image();
newimg.src = mysrc;
var def = new $.Deferred();
promises.push(def);
$.imgpreload($me, function(){
if(newimg.width > globalMaxW) {
globalMaxW = newimg.width;
}
def.resolve();
});
console.log(globalMaxW);
});
$.when.apply($, promises).done(function(){
// when all of the promises are resolved that means all imgpreload functions invoked the callbacks
// and here your globalMaxW is set.
$('#info p').css({'width' : globalMaxW});
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.