Globalna zmienna javascript wewnątrz dokumentu.gotowe

Jaki jest właściwy sposób deklarowania globalnej zmiennej javascript? Sposób, w jaki próbuję, nie działa

$(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);
Author: McGarnagle, 2012-06-22

8 answers

Jeśli deklarujesz zmienną globalną, możesz użyć jakiejś przestrzeni nazw. Po prostu zadeklaruj przestrzeń nazw Na zewnątrz, a następnie możesz wrzucić do niej, co chcesz. W ten sposób...

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

    MyProject.intro = "something";
});

console.log(MyProject.intro); // "something"
 65
Author: McGarnagle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-22 08:53:29

Declare this

var intro;

Poza $(document).ready() ponieważ, $(document).ready() ukryje Twoją zmienną przed globalnym zasięgiem.

Kod

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

Według @ Zakaria komentarz

Inny sposób:

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

Uwaga

console.log(intro);

Poza funkcją DOM ready (aktualnie masz) zaloguje się undefined, ale wewnątrz DOM ready da ci true / false.

Twój zewnętrzny console.log wykonaj przed DOM ready execute, ponieważ DOM ready execute mimo wszystko zasób pojawił się DOM ie po DOM jest przygotowany, więc myślę, że zawsze będzie absurdalny wynik.


Według komentarza @w0rldart

Muszę użyć go poza funkcją DOM ready

Możesz użyć następującego podejścia:

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

Po zmianie wartości intro wywołałem funkcję, która odpali nową wartość intro.

 29
Author: thecodeparadox,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-22 09:33:48

JavaScript ma Zakres zmiennej na poziomie funkcji , co oznacza, że będziesz musiał zadeklarować swoją zmienną poza $(document).ready() funkcją.

Lub alternatywnie, aby zmienna miała Globalny Zakres, po prostu nie używaj słowa kluczowego var przed nim, jak pokazano poniżej. Jednak ogólnie jest to uważane za złą praktykę , ponieważ zanieczyszcza zasięg globalny, ale to do ciebie należy decyzja.

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

Aby dowiedzieć się więcej na ten temat, sprawdź out:

 14
Author: Sarfraz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-22 09:03:02

Użyj window.intro wewnątrz $(document).ready().

 7
Author: xdazz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-22 08:53:03

Tak: umieść intro poza dokument gotowy, dobra dyskusja tutaj: http://forum.jquery.com/topic/how-do-i-declare-a-global-variable-in-jquery @thecodeparadox jest zajebiście szybki :p tak czy inaczej!

 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>');
            }
        }
    });
});
 2
Author: Tats_innit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-22 08:52:00

W przeciwieństwie do innych języków programowania, każda zmienna zadeklarowana poza dowolną funkcją automatycznie staje się globalna,

<script>

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

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

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

</script>

Problem polega na tym, że deklarujesz zmienną wewnątrz ready() funkcji, co oznacza, że staje się ona widoczna (w zakresie) tylko wewnątrz ready() funkcji, ale nie na zewnątrz,

Rozwiązanie: Więc zrób to globalnie, tzn. zadeklaruj to na zewnątrz $(document).ready(function(){});

 2
Author: Yang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-22 08:59:46

Użyj window.intro = "value"; wewnątrz funkcji ready. "value" może być void 0 jeśli chcesz, aby było undefined

 1
Author: Esailija,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-22 08:52:31

Możesz zdefiniować zmienną wewnątrz funkcji document ready bez var, aby stała się zmienną globalną. W javascript każda zmienna zadeklarowana bez var automatycznie staje się zmienną globalną

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

Chociaż nie można użyć zmiennej natychmiast, ale będzie ona dostępna dla innych funkcji

 1
Author: Joshua,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-28 06:10:28