2016-07-21 49 views
-1

此代碼用於JavaScript中的學習目的。我已聲明瞭一個名爲num的全局變量並將其初始化爲30.現在,點擊加號按鈕時該值會增加,並且會減少點擊減號按鈕。但是當我點擊加號按鈕兩次。它提醒31兩次,而不是顯示31先,然後32。從事件處理程序方法返回後調用window.onload

當我在鉻上調試它,我發現斷點再次訪問'var num = 30'一旦它執行了被稱爲onclick加號按鈕的增加方法。 ? 那麼,爲什麼從法的窗口重裝有人能說明一下返回後在advance.My代碼由於是如下:

window.onload =initialize; 
var num=30; 
function initialize() 
{ 

if(!document.getElementById) return; 

var increaseButton = document.getElementById('plus'); 
increaseButton.onclick = increase; 
var decreaseButton = document.getElementById('minus'); 
decreaseButton.onclick = decrease; 
} 

function increase() 
{ 
    num++; 
    alert(num); 

} 
function decrease() 
{ 
    num++; 
    alert(num); 
} 
+0

當我在step()後面的大括號之後繼續執行代碼流程時,右上角到window.onload = initialize;我也檢查了當時num的值是未定義的。 –

+1

聽起來像你的按鈕是一個提交按鈕 – epascarello

+0

@HarshKrishna - 你對問題的描述表明你錯了。嘗試提供包含HTML **的[MCVE] **。 – Quentin

回答

0

似乎爲我工作,如果HTML是:

<button type="button" id="plus">+</button> 
<button type="button" id="minus">-</button> 

您也希望您的下降功能是:

function decrease() 
{ 
    num--; 
    alert(num); 
} 

的jsfiddle:https://jsfiddle.net/OzymandiasII/L9h1xbsr/

+0

感謝Ozymandias ...它的工作......我之前沒有在按鈕標籤上使用過type屬性。 –

相關問題