jquery - 在函数外使用变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5648028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:34:01  来源:igfitidea点击:

jquery - use a variable outside the function

jqueryvariablesdefinition

提问by user705730

How I Can use a variable outside the function where it was declared?

如何在声明它的函数之外使用变量?

$(function() {
    function init() {
        var bwr_w = $(window).width();
    }
    init();
    $('#button').click(function() {
        alert('The Browser Height is' + bwr_w);
    });
});

If I click on the button I get this error:

如果我单击按钮,则会收到此错误:

bwr_w is not defined

bwr_w 未定义

回答by Matías Fidemraizer

Just declare that variable in constructor's scope:

只需在构造函数的范围内声明该变量:

$(function() {
    var bwr_w = null;

    function init() {
        bwr_w = $(window).width();
    }

    init();

    $('#button').click(function() {
        alert('The Browser Height is' + bwr_w);
    });
});

回答by Andrei Andrushkevich

try this

尝试这个

$(function() {
  var bwr_w = 0;
  function init() {
    bwr_w = $(window).width();
  }
  init();
  $('#button').click(function() {
    alert('The Browser Height is' + bwr_w);
  });
});

回答by David says reinstate Monica

If you declare the variable outside the function, then assign a value to it insidethe function, it should be accessible elsewhere. So long as you're sure that a value will be assigned. If you're not sure, you might want to assign a default value:

如果在函数外部声明变量,然后在函数内部为其赋值,则应该可以在其他地方访问它。只要您确定将分配一个值。如果您不确定,您可能需要指定一个默认值:

$(function() {

        var bwr_w; // or 'var bwr_w = default_value;'

    function init() {
        bwr_w = $(window).width();
    }
    init();
    $('#button').click(function() {
        alert('The Browser Height is' + bwr_w);
    });
});