簡體   English   中英

使用Javascript填充HTML表

[英]Populate HTML Table using Javascript

我想使用JavaScript填充預定義的html表:

<table>
    <tr>
        <th scope="col">ID</th>
        <th scope="col">Name</th>
    </tr>
    <div id='data'/>
</table>

運用

document.getElementById('data').innerHTML = ....

但由於<div>不允許在<table>上面代碼不起作用。 實現這一目標的正確方法是什么?

而不是Div你可以使用tr和td。

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

在最基本的意義上:

<table>
 <tr>
  <th>ID</th>
  <th>Name</th>
 </tr>
 <tr>
  <td colspan="2">
   <div> LOTS O' CONTENT </div>
  </td>
 </tr>
</table>

你已經回答了自己 - 把div放在正確的位置 - 無論是在桌子內還是在外面。 javascript會起作用,div是否會顯示在你想要的地方,是一個不同的問題:)

暫無
暫無

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

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