简体   繁体   中英

creating table via document.onload won't function

I'm wondering as to why the following ceases to function, for whatever peculiar reason:

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

Any help would be greatly appreciated!

You all have my sincere thanks for offering your solutions: :D

Are you sure you don't mean window.onload ?

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

http://jsfiddle.net/rzfuG/

EDIT

With some extra html created for demonstration purposes:

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/

EDIT 2

Now, if you're thinking of the body tag's onload attribute, you could do:

<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/

Note, however, this is the same as window.onload . In fact, you can't do both window.onload=... and <body onload="... , since the body onload will override the JS and only one will run.

See http://jsfiddle.net/rzfuG/3/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM