为什么我不能使用 JavaScript 和

Why can't I make a Table row using JavaScript and a <div>?

本文关键字:JavaScript 不能 为什么      更新时间:2023-09-26
创建一个表行。

由于某种原因,以下代码段无法在我的html文档中插入额外的表格。文本只是随机位于表格顶部而不是 IN 表格。任何想法为什么它不起作用?

<!DOCTYPE html>
<head>
<script type = "text/javascript">
    function insertTable() {
    var table = document.getElementById("houseListingTable").innerHTML;
    table = table + "<tr><td>58,500</td><td>Montreal</td></tr>";
    }
</script>
</head>
<body>
<table>
    <tr>
        <th>Price</th>
        <th>Location</th>
    </tr>
    <div id = "houseListingTable">
    </div>
</table>
<button onclick = "insertTable()">Insert Table<'button>
</body>
</html>

为什么当我单击Insert Table按钮时,表格行没有将自己添加到我的表格中?任何帮助不胜感激!!

这里有两个问题:

  • <div> 元素直接放在<table>内是无效的 HTML。
  • 这里的table变量只是一个字符串。覆盖它对 DOM 没有影响。

要修复它:

  1. 移除<div>并为<table>提供 ID:
<table id="houseListingTable">
<tr>
    <th>Price<'th>
    <th>Location<'th>
</tr>
</table>
  1. 使用此 JavaScript:
var table = document.getElementById("houseListingTable");
table.innerHTML += "<tr><td>58,500</td><td>Montreal</td></tr>";

请注意我实际上是如何覆盖表的 .innerHTML 属性的。这是与你那里所拥有的重要区别。

在回答之前只是几条评论。请注意,您在乞讨时缺少 html 标签,并且您使用了不正确的栏"''"来关闭表格标题(应为 )和按钮标签()中的标签。

此外,表中的div 不正确。

代码不执行任何操作,因为该函数仅获取 innerHTML。出于您的目的,该函数应获取表中的内容,添加一行,然后将其粘贴回表中。

<!DOCTYPE html>
<html>
<head>
    <script type = "text/javascript">
        function insertTable() {
            var table = document.getElementById("houseListingTable").innerHTML;
            table = table + "<tr><td>58,500</td><td>Montreal</td></tr>";
            document.getElementById("houseListingTable").innerHTML = table;
        }
    </script>
</head>
<body>
    <table id="houseListingTable">
        <tr>
            <th>Price</th>
            <th>Location</th>
        </tr>
    </table>
    <button onclick = "insertTable()">Insert Table</button>
</body>
</html>

你的HTML坏了。结束标记错误。

<table id="houseListingTable">
    <tr>
        <th>Price</th>
        <th>Location</th>
    </tr>
</table>  

您可以使用 DOM 方法的 insertRow 通过先按 Id 获取表来向表添加行

function insertTable() {
          // Find a <table> element with id="houseListingTable":
        var table = document.getElementById("houseListingTable");
        // Create an empty <tr> element and add it to the table:
       var row = table.insertRow(table.rows.length);

        // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        // Append a text node to the cell1
        var price  = document.createTextNode('58,500')
        cell1.appendChild(price);
        // Append a text node to the cell2
        var location  = document.createTextNode('Montreal')
        cell2.appendChild(location);
        }