jQuery-在函数外使用变量 [英] jquery - use a variable outside the function

查看:131
本文介绍了jQuery-在函数外使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

只需在构造函数的作用域中声明该变量:

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

这篇关于jQuery-在函数外使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆