我使用此代码在按下按钮时发生一些事情:
function serverSettingsButton(){
console.log("test");
};
document.getElementById("server-settings-button").addEventListener("click", serverSettingsButton);
我从按钮得到的输出为零,甚至没有错误,就好像我从未添加过事件监听器一样。
这是按钮的 HTML:
<button id="server-settings-button" style="margin-left: 50%;font-size: xx-large;position: absolute;">Server Settings</button>
而且,如果它很重要,我的页面会像这样加载:
document.getElementsByTagName("html")[0].innerHTML = data
我到处都找过了,但找不到任何关于这个的信息。
我尝试过使用
onclick="serverSettingsButton()"
,我尝试过使用 window.serverSettingsButton = function(){}
以及几乎任何其他你能想到的为按钮分配功能的方式,但它们似乎都不起作用。
您的代码无法正常工作的原因是您尝试在 DOM 完全加载之前将事件侦听器附加到 id 为“server-settings-button”的按钮。
解决方法如下:-
// Wait for the DOM to fully load before attaching the event listener
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("server-settings-button").addEventListener("click", serverSettingsButton);
});
只需用您的代码更新它,它就应该可以工作。
运行代码:-
function serverSettingsButton(){
console.log("test");
};
// Wait for the DOM to fully load before attaching the event listener
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("server-settings-button").addEventListener("click", serverSettingsButton);
});
<html>
<body>
<button id="server-settings-button" style="margin-left: 50%;font-size: xx-large;position: absolute;">Server Settings</button>
</body>
</html>