2016-03-18 18 views
0

我有一個變量的範圍問題的代碼Javascript和JQuery的大教堂全局變量範圍

var ButtonPressed; //global SCOPE 
$(document).ready(function() 
{ 

    function messageAlert() 
    { 
    $('#buttons').append('<input type="button" id="btn" value="Clickme" />'); 
    return false; 
    } 

    messageAlert(); 

    $('#btn').on("click", function() 
    { 
    ButtonPressed = 1; 
    }); 
}); //end document 

//// UNDEFINED NOT WORKING 
if (ButtonPressed === 1) 
{ 
    alert(ButtonPressed); 
} 

我試着約範圍教程的一切,但我不能顯示變量ButtonPressed=1 GLOBAL。

任何幫助?

+2

那是'if'聲明實際上在'$(文件)。就緒()'語句之後?在這種情況下,它不會顯示警報,因爲在實際點擊按鈕之前,此代碼將始終運行。 – mikeyq6

+0

你想做什麼? – putvande

+0

只是將默認值分配給ButtonPressed變量,如:'var ButtonPressed = 0;' –

回答

2

您正將一個點擊事件綁定到按鈕#btn以設置全局變量ButtonPressed,除非您單擊此按鈕,否則它將不會被解僱。

當你的代碼執行和到達塊(這是在全球範圍內)明知按鈕沒有被點擊

if (ButtonPressed === 1) 
{ 
    alert(ButtonPressed); 
} 

變量ButtonPressed將不會設置,因爲你沒有點擊該按鈕所以它不會提醒任何消息。

換句話說,if語句運行點擊處理程序之前

0

解釋你的代碼。執行進入這種方式(1) - >(2) - >(3)

var ButtonPressed; // executed as soon as the script tag is hit -- (1) 

    $(document).ready(function() 
    { 
    //......   //executed ONLY AFTER the DOM is ready - (3) 
    }); 


    if (ButtonPressed === 1) //executed as soon as the script tag is hit - (2) 
    { 
     alert(ButtonPressed); 
    } 

作爲評論表明,所述var ButtonPressed首先執行,然後執行跳到if檢查。只有在DOM完全準備就緒後,您的代碼塊纔會執行$(document).ready

因此,這意味着所有的全球範圍內的代碼的東西會先被執行,然後一個人裏面的文件準備


1)如果你的目的是要顯示一個警告當過一個按鈕單擊了然後做這個

$('#btn').on("click", function() 
    { 
    ButtonPressed = 1; 
    alert(ButtonPressed); 
    // do all the stuff that should happen when a button is clicked 
    }); 

2)否則如果你的意圖是檢查一下按鈕是否被點擊?然後你可以使用setInterval。使用這個你可以檢查一個按鈕是否被點擊或不是每一個說1秒。如下所示。

var checkButtonStatus = setInterval(function(){ 
       if (ButtonPressed === 1) 
       { 
        alert(ButtonPressed); 
        //do all your stuff as the button was clicked 
        clearInterval(checkButtonStatus); // remove interval as you don't need to check again. 
       } 

       }, 1000); 

注:I would say option 2 is not efficient way of doing it, Go for option 1

+1

這與KAD在答案中解釋的內容有何不同? – putvande

+0

其解釋的方式,我不覺得新手會更好地理解KAD的答案,這聽起來不高。所以我解釋得越低越好 –