【问题标题】:Populate HTML Table using Javascript使用 Javascript 填充 HTML 表
【发布时间】:2011-06-08 14:35:00
【问题描述】:

我想使用 JavaScript 填充预定义的 html 表:

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

使用

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

但是由于&lt;div&gt; 不允许在&lt;table&gt; 内部,所以上面的代码不起作用。实现这一目标的正确方法是什么?

【问题讨论】:

  • 嗯,我无法想象这就是您要寻找的答案,但是...不要将&lt;div /&gt; 放在&lt;table /&gt; 中?
  • 我怀疑您想要引用表格中的单个单元格,而不是把“div”放在所有地方。之前已经在 SE 上问过这个问题:stackoverflow.com/questions/3065342/… 第一个答案应该在这里对您有所帮助。

标签: javascript html-table


【解决方案1】:

您可以使用 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>

【讨论】:

    【解决方案2】:

    在最基本的意义上:

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

    【讨论】:

      【解决方案3】:

      您已经回答了自己 - 将 div 放在正确的位置 - 在桌子内部或外部。 javascript 将起作用,div 是否会显示在您想要的位置,这是一个不同的问题:)

      【讨论】:

        猜你喜欢
        • 2015-10-24
        • 2019-04-23
        • 2011-10-08
        • 1970-01-01
        • 2020-03-23
        • 1970-01-01
        • 1970-01-01
        • 2014-10-12
        • 1970-01-01
        相关资源
        最近更新 更多