document.ready中的全局JavaScript变量 [英] Global javascript variable inside document.ready

查看:261
本文介绍了document.ready中的全局JavaScript变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是宣布全局JavaScript变量的正确方法吗?我尝试它的方式不起作用

Which is the right way of declaring a global javascript variable? The way I'm trying it, doesn't work

$(document).ready(function() {

    var intro;

    if ($('.intro_check').is(':checked')) {
        intro = true;
        $('.intro').wrap('<div class="disabled"></div>');
    };

    $('.intro_check').change(function(){
        if(this.checked) {
            intro = false;
            $('.enabled').removeClass('enabled').addClass('disabled');
        } else {
            intro = true;
            if($('.intro').exists()) {
                $('.disabled').removeClass('disabled').addClass('enabled'); 
            } else {
                $('.intro').wrap('<div class="disabled"></div>');
            }
        }
    });
});

console.log(intro);


推荐答案

如果你声明一个全局变量,想要使用某种名称空间。只需在外部声明命名空间,然后就可以将任何想要的东西扔进它。像这样......

If you're declaring a global variable, you might want to use a namespace of some kind. Just declare the namespace outside, then you can throw whatever you want into it. Like this...

var MyProject = {};
$(document).ready(function() {
    MyProject.intro = "";

    MyProject.intro = "something";
});

console.log(MyProject.intro); // "something"

这篇关于document.ready中的全局JavaScript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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