簡體   English   中英

通過 document.onload 創建表不會 function

[英]creating table via document.onload won't function

我想知道為什么以下內容停止為 function,無論出於何種特殊原因:

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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM