Javascript onclick 事件在重新加载页面时启动

Javascript onclick event starts when reloading page

我想通过 JavaScript 通过构造函数创建一个 Button。一切正常,但 onclick 事件在加载页面后立即开始,而不是在单击按钮后开始。

function Button(text) {
    this.button = document.createElement('button');
    this.button.id = text;
    this.button.innerHTML = text;
    this.button.style.width = 100;
    this.button.style.height = 30;
    document.body.appendChild(this.button);
};

b1 = new Button('button1');
b1.onclick = alert('hello');

它将在加载时启动,因为您使用 alert('hello').

显式调用它

更好"wrap"它:

b1.onclick = function() {
  alert('hello')
}

通过这种方式,您可以将 function 分配给 b1.onclick 事件,并且该函数将在单击按钮时调用。

在您的代码中,您正在调用 alert,并将其 return 值分配给 b1.onclick

function Button(text) {
    this.button = document.createElement('button');
    this.button.id = text;
    this.button.innerHTML = text;
    this.button.style.width = 100;
    this.button.style.height = 30;
    document.body.appendChild(this.button);
};

b1 = new Button('button1');
b1.onclick = function() { 
  //Handle click here
  alert("hello");
};

b1.onclick 应该是一个函数。

当你说 b1.onclick = alert("hello"); 时,它认为你想要任何 alert() 函数 returns 进入 b1.onclick,所以它会 运行函数并找出来。你要的是这个:

b1.onclick = function(){
    alert("hello");
};

这是一个实际的函数对象,将在单击 b1 时调用。