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

どのような問題が発生しているかは 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 に答える
0

変数をグローバル変数にするか (悪い考えです)、次のようにサイズ変更ブロックを自己実行型の無名関数に移動します。

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