从嵌套的私有函数中设置全局变量

Setting a global variable from within a nested private function

本文关键字:设置 全局变量 函数 嵌套      更新时间:2023-09-26

你好,提前感谢您对这个难题的帮助!

我在$.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});
    });
}