【问题标题】:html template with jquery带有jquery的html模板
【发布时间】: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>

这里有什么问题?

【问题讨论】:

    标签: jquery templates


    【解决方案1】:

    问题在于,在每次迭代中,您都在查看原始的 #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());
        }
    };
    

    Working example

    请注意,我从您设置为 id 属性的值中删除了 #,因为它会导致您的 JS 选择器和 CSS 规则混淆。还要注意 text()prop() 方法在 html()attr() 上的使用。您还可以通过将代码修改为以下内容来充分利用 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());
        });
    });
    

    【讨论】:

    • var $host = $("#host") 和 var host = $("#host") 有什么不同吗?很抱歉这个问题,但我的目标是一个不擅长 JS 的 Java 人。
    • 没有区别,前面的$只是一个命名约定,表明该变量包含一个jQuery对象。
    • 没问题,很高兴为您提供帮助