gpt4 book ai didi

javascript - JS(template Literal-)生成html,更新DOM?

转载 作者:行者123 更新时间:2023-12-02 23:15:00 25 4
gpt4 key购买 nike

当使用 JavaScript 生成 HTML 时,使用烦人的冗长是不是更好? document.createElement("p") ...

(如下所示:https://www.w3schools.com/jsref/met_document_createelement.asp)

还是使用模板文字(反引号)更好?

`<p></p>`

我不确定模板文字是否会更新 DOM & 我假设 createElement() 会更新?

而且我不知道如何测试它。

示例代码:

<body>
<div id="myDIV"></div>

<script>

let theDiv = document.getElementById("myDIV");

function verboseGeneration(){
var para = document.createElement("P");
para.innerHTML = "This is a paragraph.";
theDiv.insertAdjacentElement("beforeend", para);
}

function TemplateLiteralGeneration(){
theDiv.insertAdjacentHTML("beforeend", `<p>This is a paragraph.</p>`)
}

verboseGeneration();
TemplateLiteralGeneration();

</script>
</body>

预期结果:它们相等。

实际结果:未知,因为我不知道如何测试它如何与 HTML DOM 交互。

(我计划基于一些数组生成一个大表,并且我对使用模板文字犹豫不决,以防它们不更新或无法与 DOM 一起正常工作,并且它会在未来。)

最佳答案

这取决于您想要对生成的标记执行什么操作。如果您想执行操作,遍历片段,那么您最好创建一个元素作为节点(使用 document.createElement() ),而不是使用纯字符串。

正如您提到的,您正在生成一个大表,实际创建一个 document fragment 可能更有意义(并且可能更高效)。保存大表的所有内容,然后将整个片段附加到空白 <table> 中元素。

这是一个示例:我想迭代创建一个 10 列宽、20 行高的表。如果选择使用纯字符串构造整个表,则字符串会变得很长,并且您无法遍历创建的表。

下面的示例显示了使用 document.createElement() 的强大功能和片段可以是:我可以通过遍历标记来追溯地将新的样式和逻辑应用于标记。你不能用普通字符串来做到这一点。在这种情况下,我选择在最后重新访问表格,并有条件地突出显示其中包含偶数数字的单元格:

const fragment = document.createDocumentFragment();
const columns = 10;
const rows = 20;

// Create table header
const header = document.createElement('thead');
const headerRow = document.createElement('tr');
for (let i = 0; i < columns; i++) {
const headerCell = document.createElement('th');
headerCell.innerHTML = `Col ${i + 1}`;
headerRow.appendChild(headerCell);
}
header.appendChild(headerRow);

// Append header to table
fragment.appendChild(header);

// Create table body
const body = document.createElement('tbody');

for (let i = 0; i < rows; i++) {
const bodyRow = document.createElement('tr');
for (let j = 0; j < columns; j++) {
const bodyCell = document.createElement('td');
bodyCell.innerHTML = i + j + 1;
bodyRow.appendChild(bodyCell);
}

body.appendChild(bodyRow);
}

// Append body to table
fragment.appendChild(body);

// Here's the advantage of storing your markup as node/elements
// You can traverse through the fragment if you want!
// Let's say I want to highlight all even numbers
const allCells = fragment.querySelectorAll('tbody td');
Array.from(allCells).forEach(cell => {
const n = +cell.innerHTML;
if (n % 2 === 0) {
cell.classList.add('highlight');
}
});

document.getElementById('my-table').appendChild(fragment);
table th,
table td {
border: 1px solid #ccc;
}

.highlight {
background-color: yellow;
}
<table id="my-table"></table>

关于javascript - JS(template Literal-)生成html,更新DOM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57202411/

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