gpt4 book ai didi

javascript - 通过 document.onload 创建表将不起作用

转载 作者:行者123 更新时间:2023-11-30 13:32:29 25 4
gpt4 key购买 nike

我想知道为什么以下内容会因任何特殊原因而停止运行:

document.onload=function() {
table = document.createElement("table");
table.setAttribute("border", "1");
document.body.appendChild(table);
};

如有任何帮助,我们将不胜感激!

我衷心感谢你们提供解决方案! :D

最佳答案

你确定你不是说 window.onload

window.onload=function() {
table = document.createElement("table");
table.setAttribute("border", "1");
document.body.appendChild(table);
};

http://jsfiddle.net/rzfuG/

编辑

为了演示目的创建了一些额外的 html:

window.onload=function() {
table = document.createElement("table");
table.setAttribute("border", "1");
document.body.appendChild(table);
tbody = document.createElement('tbody');
tr = document.createElement('tr');
td = document.createElement('td');
td.innerHTML = "test";
table.appendChild(tbody);
tbody.appendChild(tr);
tr.appendChild(td);
};

http://jsfiddle.net/rzfuG/1/

编辑 2

现在,如果您正在考虑 body 标签的 onload 属性,您可以这样做:

<body onload="my_onload();"></body>

function my_onload() {
table = document.createElement("table");
table.setAttribute("border", "1");
document.body.appendChild(table);
tbody = document.createElement('tbody');
tr = document.createElement('tr');
td = document.createElement('td');
td.innerHTML = "test";
table.appendChild(tbody);
tbody.appendChild(tr);
tr.appendChild(td);
};

http://jsfiddle.net/rzfuG/2/

但是请注意,这与 window.onload 相同.事实上,你不能两者都做 window.onload=...<body onload="... ,因为 body onload 将覆盖 JS,并且只有一个会运行。

参见 http://jsfiddle.net/rzfuG/3/

关于javascript - 通过 document.onload 创建表将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6240878/

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