[英]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.