gpt4 book ai didi

javascript - DOM加载时的attachEvent

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

我正在将 windows.onload 上的 ID 设置为 button 元素。现在我需要在该按钮上附加 onclick,但此时 ID 未定义。如何正确地做到这一点?我尝试像下面的代码那样附加事件,或者使用 attachEvent 附加事件,并尝试使用 onreadystatechangeDOMContentLoaded 进行其他一些尝试。它是 IE8 中的遗留应用程序,没有库。谢谢!

window.onload = function () {

var table = window.document.getElementById("TABLE");
var button = document.createElement("BUTTON");
table.appendChild(button);
button.id = "BUTTON_ID"; // give id attribute after append to table
var row = TABLE.tBodies[0].rows;
for (var i = 0; i < row.length; i++) {
//...
}
}

function BUTTON_ID.onclick() {

//...
}

最佳答案

您可以在创建按钮时附加事件:

window.onload = function () {

[ ... ]

var button = document.createElement("BUTTON");
button.id = "BUTTON_ID";
button.onclick = function() {
alert("Clicked");
}

table.appendChild(button);

[ ... ]
}

JsFiddle Demo

关于javascript - DOM加载时的attachEvent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32838696/

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