2014-10-20 47 views
0

只是想說這是一個什麼樣的偉大論壇,適用於開發人員和IT專業人員。根據onclick函數中定義的增量獲取全局變量?

我在下面有下面的代碼。我試圖獲取計數值正在處理的函數之外的計數值。但是,即使對該函數使用了全局變量,它也不能正常工作。 無論如何,這可以做到嗎?

感謝您的幫助球員,非常感謝。

var getcountglobal =0; 
var that =this.buttonforitem; //this refers to button created by javascript 

that.onclick = function() 
{ 

    getcountglobal++; 
    console.log(getcountglobal);// in console when clicking the button it gives 1,2,3,etc 

} 
console.log(getcountglobal); // here it gives 0 and not the click number. Why doesn't or cant the variable be changed? 
+0

你爲什麼想到第一次加載頁面在函數運行之前要更改的變量? – SLaks 2014-10-20 17:36:37

+0

對於最後一行中的拼寫錯誤,應該是:console.log(getcountglobal);謝謝 – 2014-10-20 17:36:48

+0

嗨SLaks,我認爲變量是當我點擊按鈕被改變?這將如何在代碼方面工作?謝謝 – 2014-10-20 17:38:13

回答

0

原因是,console.log(getcountergloba);無論點擊是否被執行,因爲它位於事件處理程序之外(onclick)。一旦有人點擊,該變量就會增加並顯示正確的數字。但是,當您在事件處理程序之外進行打印時,它會在發生任何事件之前執行,並且此時它的值爲0

0

發生的情況是,打印出的console.log 0在您單擊按鈕。它將點擊處理程序分配給您的按鈕後立即打印出零。

0
that.onclick = function() 
{ 

    getcountglobal++; 
    console.log(getcountglobal);// in console when clicking the button it gives 1,2,3,etc 

    console.log(getcounterglobal);//move this in your click 

} 

該變量正在每次點擊更改。問題是你唯一的印刷是在頁面加載時,全球在你點擊0

移動的console.log否則只會跑在全球= 0