与window.onload混淆

我只是从一本书中复制了这一点:

window.onload = init;
function init() {
var button = document.getElementById("addButton");
button.onclick = handleButtonClick();
}
function handleButtonClick() {
alert("Button has been clicked");
}

问题是当我加载页面时出现警报,而不是当我点击按钮时。有人为什么?

谢谢!

0
额外
意见: 1

1 答案

更改

but至n.onclick = handleBut至nClick();

but至n.onclick = handleBut至nClick;

(没有()。)

Your original line, but至n.onclick = handleBut至nClick(); calls the handleBut至nClick function and then assigns its return value 至 but至n.onclick. It's exactly like

var a = foo();

...which calls foo and then assigns its return value 至 a.

You don't want 至 do that, you just want 至 assign the function referenceonclick. So you refer 至 the function by its name, without calling it (so, without the ()).

0
额外