简体   繁体   English

如何推断变量使它们成为全局变量?

[英]How to extrapolate variables to make them become globals?

Let's say I have to find out the window width, the code will be: 假设我必须找出窗口宽度,代码将为:

$(window).width();

and if I want it to become a global variable i just have to declare its name: 如果我想让它成为一个全局变量,我只需要声明它的名字:

var windowWidth = $(window).width();

The result will be the window's width. 结果将是窗口的宽度。 But I need that variable to change when things happens, for example when I resize the window: 但是当事情发生时我需要变量来改变,例如当我调整窗口大小时:

$(window).resize(function(){
    var windowWidth = $(window).width();
});

How can I extrapolate this variable in order to override the one before? 我如何推断这个变量以覆盖之前的变量? I can override the variable before putting the function i need in the .resize(function(); but in this way my code confusionary and I need just a variable to use it in other functions outside the resize function, for example a .click(function) 我可以在.resize(function()中放入我需要的函数之前覆盖变量;但是这样我的代码混乱,我需要一个变量来在resize函数之外的其他函数中使用它,例如.click(功能)

$(document).ready(function(){
    var w = $(window).width();
    $(window).resize(function(){
        var w = $(window).width();

        //click function goes here.
    });
});

how if I want that the function above will become a whole new variable? 如果我想要上面的函数将成为一个全新的变量? without putting a new function in it? 没有放入新功能?

the problem with your code is that you have var twice. 你的代码的问题是你有两次var。 every time you use var you create a new variable. 每次使用var时都会创建一个新变量。 so just leave out the second one like this: 所以就这样省去第二个:

$(document).ready(function(){
    var w = $(window).width();
    $(window).resize(function(){
        w = $(window).width();

        //click function goes here.
    });
});

I do something similar for my projects: 我为我的项目做了类似的事情:

var winWidth, winHeight;

function setWinSize(){
    winWidth = $(window).width();
    winHeight = $(window).height();
    //note I'm not using the var suffix again
}

//then we set the new values on document ready and on window resize
$(document).ready(function(){
    setWinSize();
})
$(window).resize(function(){
    setWinSize();
})

function myCustomFunction(){
    //I can now use my vars here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM