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

时间:2014-04-30 21:53:34

标签: javascript jquery global-variables scope

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

我在globalMaxW功能中设置$.imgpreload()时遇到问题。

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});
}

2 个答案:

答案 0 :(得分:1)

你的console.log(globalMaxW)在下面的代码完成执行之前发生,是的,那时它确实等于零:

 $.imgpreload($me, function(){
            if(newimg.width > globalMaxW) {
                globalMaxW = newimg.width;
            }           
        });

由于该函数是异步的,它开始运行" imgpreload"并立即继续,而不是等待它完成。 globalMaxW将被设置,但是在console.log()...

之后

答案 1 :(得分:0)

我认为这是jquery.imgpreload插件。 imgpreload是异步的,所以你的globalMaxW是设置的,但是只有在你调用的第二个参数调用的回调函数之后才会设置,这只有在以异步方式获取图像后才会发生。我知道你只想在预加载所有图像后才设置css属性。因此,您可以使用jquery延迟对象的集合来实现此目的。

在下面的代码中,将创建jQuery $ .Deferred对象并将其推送到每个imgpreload调用的数组中。一旦imgpreload调用了回调,您就可以看到延迟已解决。

在底部$ .when函数基本上调用完成回调一次,每一个$ .Deferred在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});
    });
}
相关问题