gpt4 book ai didi

javascript - 使用 getElementById 创建表仅显示最后一个实例

转载 作者:行者123 更新时间:2023-12-02 17:36:08 25 4
gpt4 key购买 nike

我使用一个非常简单的函数在表格中显示用户通过提示窗口给出的人名及其年龄。我遇到的唯一问题是,每当用户添加第二个姓名和年龄时,JS 都会替换前一个。它不会添加第二行。

http://jsbin.com/jamobifu

JS

function table(){
var numberOfPeople = window.prompt("How many people do you want to add?");

/**/for(var count = 0; count < numberOfPeople; count++){
var name = window.prompt("Type the name of the person");
var age = window.prompt("Type their age");
document.getElementById("tableOfPeople").innerHTML += "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
}
}

HTML

<h1>Making A List</h1>
<p>This program will create a list based on two question which will be asked to you. Type the name of the person and their corresponding age. Output will be presented in a customized table.</p>
<input type="button" value="Create List" onclick="table()" />
<table id="tableOfPeople" style="width: 600px; margin-left: auto; margin-right: auto; margin-top: 50px; background-color: #74a9cb; color: white; border: 1px solid #127bbb"></table>

最佳答案

您不应该使用innerHTML 来修改表格的内容,因为它在IE 版本不超过9(其中innerHTML is readonly 表示许多与表格相关的元素*)的IE 版本中会失败。所以你应该使用 DOM insertRowinsertCell方法(或 createElementappendChild ,但插入方法一次执行两个步骤):

var row = document.getElementById("tableOfPeople").insertRow(-1);
var cell = row.insertCell(-1);
cell.appendChild(document.createTextNode(name));
cell = row.insertCell(-1);
cell.appendChild(document.createTextNode(age));

* MSDN::innerHTML property

The innerHTML property is read-only on the col, colGroup, frameSet, html, head, style, table, tBody, tFoot, tHead, title, and tr objects.

关于javascript - 使用 getElementById 创建表仅显示最后一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22598044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com