gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:52:45 24 4
gpt4 key购买 nike

我想通过 JavaScript 通过构造函数创建一个按钮。一切正常,但 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') 显式调用它。

更好地“包装”它:

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

这样您就可以将一个函数分配给b1.onclick事件,并且该函数将在单击按钮时调用。

关于Javascript onclick 事件在重新加载页面时启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32811073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com