jquery - 使用 jquery 的 html 模板

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

Working example

请注意,我从您为 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/

相关文章:

javascript - 将 mootools 代码转换为 jquery

javascript - 如何检查对象内的数组是否为空

带有模板参数的 C++ 函数分派(dispatch)

C++20 概念和模板 : fixe-size and resizable array

c++ - 为什么将函数传递给内核会导致数据变得不可变?

templates - Scala Play Framework中的导入语句不起作用

jquery - 使用 jQuery 在 Twitter Bootstrap 3 中重用页眉和页脚代码

两次引用 Jquery 时,JQuery 'Object' 未定义

javascript - 请关注我的初学者 javaScript

c++ - 将 std::function 与模板一起使用