window.onload从事件处理程序方法返回后调用

window.onload called after returning from a event handler method

本文关键字:返回 调用 方法 程序 onload 事件处理 window      更新时间:2023-09-26

此代码用于学习javascript。我已经声明了一个名为num的全局变量,并将其初始化为30。现在,点击加号按钮会增加,点击减号按钮会减少。但当我点击加号按钮两次时。它提醒31两次,而不是先显示31然后显示32。

当我在chrome上调试它时,我发现一旦它执行了名为onclick of plus按钮的increase方法,断点就会再次命中"var num=30"。那么,为什么在方法返回之后,窗口会重新加载呢?有人能解释一下吗?提前谢谢。我的代码如下:

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

如果HTML是:,似乎对我有效

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

您还希望您的递减函数为:

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

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