jquery - use a variable outside the function

喜你入骨 提交于 2019-12-01 03:39:19

问题


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


回答1:


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);
    });
});



回答2:


try this

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



回答3:


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);
    });
});


来源:https://stackoverflow.com/questions/5648028/jquery-use-a-variable-outside-the-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!