我正在尝试使用 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>
这里出了什么问题?
最佳答案
问题是因为在每次迭代中您都会查看原始的 #template
元素。第一次迭代更改 #d1
元素的 id
。在进一步的迭代中,id 选择器找不到该元素(当您更改它时),因此它会附加第一次迭代的值。
要解决这个问题,您应该在循环的每次迭代中clone()
一个#template
的新副本。试试这个:
window.onload = function() {
var $host = $("#host");
for (var i = 0; i < descriptions.length; i++) {
var description = descriptions[i];
var $template = $("#template").clone();
$template.find("div#d2").text(description.author);
$template.find("div#d1").prop("id", description.id);
$host.append($template.html());
}
};
请注意,我从您为 id
属性设置的值中删除了 #
,因为它会导致 JS 选择器和 CSS 规则出现困惑。另请注意在 html()
和 attr()
上使用 text()
和 prop()
方法。您还可以通过将代码修改为以下内容来充分利用 jQuery 的所有功能:
$(window).on('load', function() {
var $host = $("#host");
$.each(descriptions, function(i, description) {
var $template = $("#template").clone();
$template.find("div#d2").text(description.author);
$template.find("div#d1").prop("id", description.id);
$host.append($template.html());
});
});
关于jquery - 使用 jquery 的 html 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36434625/