0

每次调整窗口大小时,如何更新另一个函数中的变量?

代码如下:

$(window).resize(function() {                
    Here is the NewVarialble;
});


(function (a) {
    OldVariable;
    Want to update the OldVarible with NewVariable;
})(jQuery);
4

3 回答 3

0
var resizeMe = function (newVar) {
    var oldVar = newVar;
}

$(window).resize(function (r) {  
    console.log(r);
    var newV = r;           
    resizeMe(newV);
});
于 2012-10-14T09:22:32.313 回答
0

要么使变量成为全局变量(坏主意),要么将调整大小块移动到自执行匿名函数中,如下所示:

(function (a) {
    OldVariable;
    $(window).resize(function() {                
        this now has access to oldvariable
    });    
})(jQuery);
于 2012-10-14T09:47:59.253 回答
0

目前还不是 100% 清楚您遇到了什么问题,但似乎只是关于范围。

这可能对范围等有用的阅读 http://javascript.crockford.com/code.html

这是一个工作版本 - 在 js 上使用下面粘贴的代码,我不建议在窗口对象上使用变量,它只是为了演示

http://jsfiddle.net/6B93N/

    $(document).ready(function(){// wrapper function / scope change as appropriate

        window.OldVariable =  -1; // placed globally but change as appropriate

        $(window).resize(function() {
            var NewVariable; // null initially

            NewVariable = Math.random();// assign a random number
            updateOldVar(NewVariable);
        });


        function updateOldVar(a) {
            window.OldVariable = a;
            //console.log(window.OldVariable);
        }


        $('.testbtn').on('click', function() {
           console.log(window.OldVariable);
        });



    });

进一步 编辑下面的评论:

    $(document).ready(function () {// wrapper function / scope change as appropriate

        var d = {
          divalayerWidth: 0,
          divalayerHeight: 0
        };

        $(window).resize(onWindowResize);

        function onWindowResize(e){
            updateD(d, e.target.outerWidth, e.target.outerHeight);
        }

        function updateD(d, w, h){

            d.divalayerWidth = w;
            d.divalayerHeight = h;
        }

    });
于 2012-10-14T09:45:01.187 回答