document.ready 中的全局 javascript 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11152977/
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-24 04:42:13  来源:igfitidea点击:

Global javascript variable inside document.ready

javascriptjqueryglobal-variablesscope

提问by Alex

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

哪个是声明全局 javascript 变量的正确方法?我正在尝试的方式不起作用

$(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);

回答by McGarnagle

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"

回答by thecodeparadox

declare this

声明这个

var intro;

outside of $(document).ready()because, $(document).ready()will hide your variable from global scope.

$(document).ready()因为之外,$(document).ready()将从全局范围隐藏您的变量。

Code

代码

var intro;

$(document).ready(function() {
    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>');
            }
        }
    });
});


According to @Zakaria comment

根据@Zakaria 评论

Another way:

其它的办法:

window.intro = undefined;

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


Note

笔记

console.log(intro);

outside of DOM ready function (currently you've) will log undefined, but within DOM ready it will give you true/ false.

在 DOM ready 函数之外(目前你已经)将 log undefined,但在 DOM ready 内它会给你 true/false。

Your outer console.logexecute before DOM ready execute, because DOM ready execute after all resource appeared to DOM i.e after DOM is prepared, so I think you'll always get absurd result.

你的外层console.log在 DOM 准备好执行之前执行,因为 DOM 准备好在所有资源出现在 DOM 之后执行,即在 DOM 准备好之后,所以我认为你总是会得到荒谬的结果。



According to comment of @W0rldart

根据@W0rldart 的评论

I need to use it outside of DOM ready function

我需要在 DOM 就绪函数之外使用它

You can use following approach:

您可以使用以下方法:

var intro = undefined;

$(document).ready(function() {
    if ($('.intro_check').is(':checked')) {
        intro = true;
        introCheck();
        $('.intro').wrap('<div class="disabled"></div>');
    };
    $('.intro_check').change(function() {
        if (this.checked) {
            intro = true;
        } else {
            intro = false;
        }
        introCheck();
    });

});

function introCheck() {
    console.log(intro);
}

After change the value of introI called a function that will fire with new value of intro.

更改 的值后,intro我调用了一个函数,该函数将以 的新值触发intro

回答by Sarfraz

JavaScript has Function-Levelvariable scope which means you will have to declare your variable outside $(document).ready()function.

JavaScript 具有函数级变量作用域,这意味着您必须在$(document).ready()函数之外声明变量。

Or alternatively to make your variable to have globalscope, simply dont use varkeyword before it like shown below. However generally this is considered bad practicebecause it pollutesthe global scope but it is up to you to decide.

或者,为了使您的变量具有全局范围,只需不要var在它之前使用关键字,如下所示。但是,通常这被认为是不好的做法,因为它会污染全局范围,但由您决定。

$(document).ready(function() {
   intro = null; // it is in global scope now


To learn more about it, check out:

要了解更多信息,请查看:

回答by xdazz

Use window.introinside of $(document).ready().

window.intro内部使用$(document).ready()

回答by Joshua

You can define the variable inside the document ready function without var to make it a global variable. In javascript any variable declared without var automatically becomes a global variable

您可以在没有 var 的文档就绪函数中定义变量,使其成为全局变量。在 javascript 中,任何没有 var 声明的变量都会自动成为全局变量

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

although you cant use the variable immediately, but it would be accessible to other functions

虽然您不能立即使用该变量,但它可以被其他函数访问

回答by Yang

Unlike another programming languages, any variable declared outside any function automatically becomes global,

与其他编程语言不同,在任何函数之外声明的任何变量都会自动变为全局变量,

<script>

//declare global variable
var __foo = '123';

function __test(){
 //__foo is global and visible here
 alert(__foo);
}

//so, it will alert '123'
__test();

</script>

You problem is that you declare variable inside ready()function, which means that it becomes visible (in scope) ONLY inside ready()function, but not outside,

你的问题是你在ready()函数内部声明变量,这意味着它只在ready()函数内部可见(在范围内),而不是外部,

Solution: So just make it global, i.e declare this one outside $(document).ready(function(){});

解决方案:所以只需将其设为全局,即在外面声明这个 $(document).ready(function(){});

回答by Tats_innit

like this: put introoutside your document ready, Good discussion here: http://forum.jquery.com/topic/how-do-i-declare-a-global-variable-in-jquery@thecodeparadox is awesomely fast :P anyways!

像这样:把intro你的文档放在外面准备好,这里有很好的讨论:http: //forum.jquery.com/topic/how-do-i-declare-a-global-variable-in-jquery@thecodeparadox 非常快:无论如何!

 var intro;

$(document).ready(function() {



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

回答by Esailija

Use window.intro = "value";inside the ready function. "value"could be void 0if you want it to be undefined

使用window.intro = "value";准备函数内部。"value"可能是,void 0如果你愿意的话undefined