jquery - use a variable outside the function

后端 未结 3 1004
执笔经年
执笔经年 2021-01-13 06:35

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

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


        
3条回答
  •  灰色年华
    2021-01-13 07:25

    If you declare the variable outside the function, then assign a value to it inside the 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);
        });
    });
    

提交回复
热议问题