使用 Javascript 填充 HTML 表格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6280495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Populate HTML Table using Javascript
提问by Chris
I want to populate a predefined html table using JavaScript:
我想使用 JavaScript 填充预定义的 html 表:
<table>
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
</tr>
<div id='data'/>
</table>
using
使用
document.getElementById('data').innerHTML = ....
But since <div>
is not allowed inside of <table>
above code doesn't work. What is the correct way to achieve this?
但是由于<div>
不允许在<table>
上面的代码中不起作用。实现这一目标的正确方法是什么?
回答by Kamahire
Instead of Div you can use tr and td.
您可以使用 tr 和 td 代替 Div。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html>
<head>
<script type="text/javascript">
function addRow(content,morecontent)
{
if (!document.getElementsByTagName) return;
tabBody=document.getElementsByTagName("tbody").item(0);
row=document.createElement("tr");
cell1 = document.createElement("td");
cell2 = document.createElement("td");
textnode1=document.createTextNode(content);
textnode2=document.createTextNode(morecontent);
cell1.appendChild(textnode1);
cell2.appendChild(textnode2);
row.appendChild(cell1);
row.appendChild(cell2);
tabBody.appendChild(row);
}
</script>
</head>
<body>
<table border='1' id='mytable'>
<tbody>
<tr><td>22</td><td>333</td></tr>
<tr><td>22</td><td>333</td></tr>
</tbody>
</table>
<button onClick='addRow("123","456");return false;'>
Add Row</button>
</body>
</html>
回答by josh.trow
In the most basic sense:
在最基本的意义上:
<table>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tr>
<td colspan="2">
<div> LOTS O' CONTENT </div>
</td>
</tr>
</table>
回答by Nikoloff
You've answered yourself - put the div in the right location - either inside the table or outside. The javascript will work, whether the div will be displayed where you'd like it to, is a different question :)
你已经回答了自己 - 将 div 放在正确的位置 - 无论是在桌子里面还是外面。javascript 会起作用,div 是否会显示在您想要的位置,这是一个不同的问题:)