从嵌套的私有函数中设置全局变量
Setting a global variable from within a nested private function
你好,提前感谢您对这个难题的帮助!
我在$.imgpreload()
函数中设置globalMaxW
时遇到问题。
console.log(globalMaxW);
在$.imgpreload()
函数之后调用时返回0
,而在$.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函数基本上每$.Delated调用一次done回调。promise集合中的Deferred被解析。
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});
});
}
相关文章:
- 在javascript函数中设置全局变量
- 如何从onclick函数设置全局变量并将其传递给另一个JS文件
- 使用eval()设置全局变量
- Ajax设置全局变量,但外部值消失
- 更新后,父视图未在 Electron 中的
上设置全局变量 - 为什么在定义回调/侦听器函数(异步消息传递,port.on)后没有立即设置全局变量
- 如何在不设置全局变量的情况下确定是否已调用函数
- 在函数内设置全局变量
- jQuery / JS设置全局变量,但卡在传递给AJAX自定义函数
- 在 jsdom 加载的脚本中设置全局变量
- 设置全局变量,但未获得预期结果
- 延迟调用 dojo widget 中的函数,直到设置全局变量
- 如何在Javascript中设置全局变量
- ngresource在成功响应中设置全局变量
- 如何在点击事件中设置全局变量
- 通过future函数循环和设置全局变量
- 尝试用javascript函数设置全局变量
- jQuery Ajax Post -无法使用回调函数设置全局变量
- jQuery load()函数不设置全局变量
- 设置全局变量并在jquery/javascript中访问它