gpt4 book ai didi

javascript - 使用 javascript 一次添加多个 HTML 元素

转载 作者:行者123 更新时间:2023-11-30 20:09:36 24 4
gpt4 key购买 nike

我正在尝试添加 4 个“tr”元素,每个元素包含 4 个“td”元素,但我不太清楚该怎么做。我可以用单个 td 添加单个 tr,但不能添加多个。

这是我的不完整代码。问题出在我写的“//HERE IS THE PROBLEM!!!”的地方。非常感谢任何帮助。

/* ///// INITIAL TITLE ///// */
var initialTitle = document.createElement("h1");
var intialTitleContent = document.createTextNode("Please press the \"1\" key on your keyboard.");
initialTitle.appendChild(intialTitleContent);
document.body.appendChild(initialTitle);

/* ///// KEYDOWN CODE ///// */

window.addEventListener("keydown", checkKeyPress, false);
function checkKeyPress(key) {

if (key.keyCode == "49") // "1"
{
var pElement = document.createElement("p");
var content = document.createTextNode("Welcome! This page is
made entirely out of javascript. It is completely impractical
to create a webpage in this manner. This page is simply a
demonstration of how javascript can be used to create and add
HTML elementS and CSS to a HTML document. You can add content
by pressing the \"1\" through to \"9\" keys.");

pElement.appendChild(content);
document.body.appendChild(pElement);
}

// HERE IS THE PROBLEM!!!

else if (key.keyCode == "50") // "2"
{
var i;
var tableDiv = document.createElement("div");
tableDiv.classList.add("div_1");
var tableElement = document.createElement("table");
var trElements = document.createElement("tr");
var tdElements = document.createElement("td");
tdElements.classList.add("tableCell");
for (i = 0; i < 4; i++) {
var multi =
tableDiv.appendChild(tableElement);
tableElement.appendChild(trElements);
trElements.appendChild(tdElements);
}
document.body.appendChild(multi);
<!doctype html>
<html lang="en-gb">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, intital-scale= 1.0" />
<title>Javascript Only Site</title>
</head>
<body>

<script src="JOS.js"></script>

</body>
</html>

最佳答案

您应该在循环内创建 tdElement,然后附加到 trElement。还将 trElementtableElement 附加到循环外的 tableDiv

window.onload = function()
{
var tableDiv = document.createElement("div");
var tableElement = document.createElement("table");
var trElement = document.createElement("tr");

tableDiv.classList.add("div_1");
tableElement.setAttribute("border","1");

for(var i = 1; i <= 4; i++)
{
var tdElement = document.createElement("td");

tdElement.innerText = i;
tdElement.classList.add("tableCell");
trElement.appendChild(tdElement);
}

tableElement.appendChild(trElement);
tableDiv.appendChild(tableElement);

document.body.appendChild(tableDiv);
}
<html>
<body>
</body>
</html>

关于javascript - 使用 javascript 一次添加多个 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52537711/

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