gpt4 book ai didi

javascript - 如何使用javascript将数据放入HTML表格

转载 作者:行者123 更新时间:2023-11-30 16:21:02 24 4
gpt4 key购买 nike

HTML 文件:

<body>
<table id="tblUser"></table>
</body>

Javascript:

var userName="Tom";
var age= "21";
//now to put these data into a table

现在,如何将 Javascript 中的数据放入表中,使其看起来像这样

Name - AgeTom    21

最佳答案

你应该使用 createElement() appendChild() ,检查下面的示例。

希望这对您有所帮助。


var table = document.getElementById('tblUser');
var userName="Tom";
var age= "21";

var tr = document.createElement('tr');

var td_1 = document.createElement('td');
var td_2 = document.createElement('td');

var text_1 = document.createTextNode('Name');
var text_2 = document.createTextNode('Age');

td_1.appendChild(text_1);
td_2.appendChild(text_2);
tr.appendChild(td_1);
tr.appendChild(td_2);

table.appendChild(tr);

var tr_2 = document.createElement('tr');

var td_3 = document.createElement('td');
var td_4 = document.createElement('td');

var text_3 = document.createTextNode(userName);
var text_4 = document.createTextNode(age);

td_3.appendChild(text_3);
td_4.appendChild(text_4);
tr_2.appendChild(td_3);
tr_2.appendChild(td_4);

table.appendChild(tr_2);

document.body.appendChild(table);
<table id="tblUser" border=1></table>

关于javascript - 如何使用javascript将数据放入HTML表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34741352/

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