出于某种原因,以下代码无法将额外的表格插入到我的 html
文档中。文本只是随机坐在表格的顶部而不是在表格中。知道为什么它不起作用吗?
<!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 没有影响。
修复它:
- 删除
<div>
并给出<table>
一个ID:
<table id="houseListingTable">
<tr>
<th>Price<\th>
<th>Location<\th>
</tr>
</table>
- 使用这个 JavaScript:
var table = document.getElementById("houseListingTable");
table.innerHTML += "<tr><td>58,500</td><td>Montreal</td></tr>";
请注意我实际上是如何覆盖表的 .innerHTML
的属性(property)。这是与您那里的重要区别。
关于javascript - 为什么我不能使用 JavaScript 和 <div> 创建表格行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28133404/