我正在尝试使用 HTML 文档中定义的按钮的 onclick
事件将行和标题附加到 HTML 表格元素。虽然它成功添加了标题和行,但未能将行的第一个元素与标题对齐,并且页面以如下格式呈现表格:
下面是通过附加行和标题来更新/添加记录到表的 JavaScript 方法:
function updateTable(){
var usr = JSON.parse(localStorage.getItem('user'));
var i = testObject.length-1;
var header = document.createElement("th");
var usernode = document.createElement("td");
var usertext = document.createTextNode("Username");
usernode.appendChild(usertext);
header.appendChild(usernode);
var enode = document.createElement("td");
var etext = document.createTextNode("Email");
enode.appendChild(etext);
header.appendChild(enode);
var pnode = document.createElement("td");
var ptext = document.createTextNode("Password");
pnode.appendChild(ptext);
header.appendChild(pnode);
var lnode = document.createElement("td");
var ltext = document.createTextNode("Location");
lnode.appendChild(ltext);
header.appendChild(lnode);
var onode = document.createElement("td");
var otext = document.createTextNode("Organization");
onode.appendChild(otext);
header.appendChild(onode);
var noder = document.createElement("tr");
var nodeu = document.createElement("td");
var textu = document.createTextNode(usr[i].uname);
nodeu.appendChild(textu);
noder.appendChild(nodeu);
var nodee = document.createElement("td");
var texte = document.createTextNode(usr[i].email);
nodee.appendChild(texte);
noder.appendChild(nodee);
var nodep = document.createElement("td");
var textp = document.createTextNode(usr[i].pass);
nodep.appendChild(textp);
noder.appendChild(nodep);
var nodel = document.createElement("td");
var textl = document.createTextNode(usr[i].loc);
nodel.appendChild(textl);
noder.appendChild(nodel);
var nodeo = document.createElement("td");
var texto = document.createTextNode(usr[i].org);
nodeo.appendChild(texto);
noder.appendChild(nodeo);
if(document.getElementById("t").querySelector("th")==null){
document.getElementById("t").appendChild(header);
}
document.getElementById("t").appendChild(noder);
clear();
}
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="form.css">
</head>
<body>
<script src="form.js"></script>
<p id="test"></p>
<div id="userdiv">
<input type="text" placeholder="Username" id="uname">
</div>
<div id="maildiv">
<input type="text" placeholder="Email" id="email">
</div>
<div id="passdiv">
<input type="text" placeholder="Password" id="pass">
</div>
<div id="locdiv">
<input type="text" placeholder="Location" id="loc">
</div>
<div id="orgdiv">
<input type="text" placeholder="Organization" id="org">
</div>
<div id="gen">
<input type="radio"/> Male
<input type="radio"/> Female
</div>
<button id="submit" onclick="save()">Submit</button>
<table id="t" border="1">
</table>
</body>
</html>
最佳答案
您为标题使用了错误的元素。
“TH”相当于“TD”,它是一个单元格,位于“TR”内。
您在 TH 中添加 TD,实际上您需要在 TR 中添加 TH。因此,将 createdElement('th')
更改为 createElement('tr')
并将 createElement('td')
更改为 createElement ('th')
.
我还建议您在表格中使用 THEAD 和 TBODY 标签。
关于javascript - 无法在 appendchild 之后将表行与标题对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54848769/