带有jquery的html模板

带有jquery的html模板,jquery,templates,Jquery,Templates,我正在尝试使用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 descrip

我正在尝试使用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());
    }
}
var描述=[
{'id':'1','author':'Joe'},
{'id':'2','author':'Mary'},
{'id':'3','author':'Eric'}
];
//当页面完全加载时执行
window.onload=函数(){
变量主机=$(“#主机”);
var模板=$(“#模板”);
对于(变量i=0;i
除了更改id部分外,它工作正常。 每个插入的部件都有相同的id:#1”,但我可以在控制台日志中看到正确的内容:#1、#2、#3


一线
乔
一线
玛丽
一线
埃里克

这里出了什么问题?

问题在于,在每次迭代中,您都会看到原始的
#模板
元素。第一次迭代更改
#d1
元素的
id
。在进一步的迭代中,id选择器找不到该元素(当您更改它时),因此它将附加第一次迭代的值

要解决这个问题,您应该在循环的每个迭代中
clone()
一个新的
模板副本。试试这个:

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());
    }
};

var$host=$(“#host”)和var host=$(“#host”)之间有什么不同吗?很抱歉问这个问题,但我的目标是一个java家伙不擅长JS。没有任何区别,前面的
$
只是一个命名约定,表明该变量包含一个jQuery对象。没问题,很乐意提供帮助
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());
    }
};
$(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());
    });
});