【发布时间】:2025-12-26 12:30:12
【问题描述】:
我正在尝试使用 jquery 创建一个简单的 html 模板,如下所示:
<div id="template" style="display: none">
<div id="d1">1st line</div>
<div id="d2">last line</div>
</div>
<div id="host"></div>
javascript:
var descriptions = [
{'id': '1', 'author': 'Joe'},
{'id': '2', 'author': 'Mary'},
{'id': '3', 'author': 'Eric'}
];
// execute when page has fully loaded
window.onload = function () {
var host = $("#host");
var template = $("#template");
for (var i = 0; i < descriptions.length; i++) {
var description = descriptions[i];
var id = "#" + description.id;
console.log(id);
template.find("div#d2").html(description.author);
template.find("div#d1").attr("id", id);
host.append(template.html());
}
}
除了更改 id 部分外,它工作正常。 每个插入的部分都有相同的 id:“#1”,但我可以在控制台日志中看到正确的内容:#1、#2、#3
<div id="host">
<div id="**#1**">1st line</div>
<div id="d2">Joe</div>
<div id="**#1**">1st line</div>
<div id="d2">Mary</div>
<div id="**#1**">1st line</div>
<div id="d2">Eric</div>
</div>
这里有什么问题?
【问题讨论】: