简体   繁体   English

使用JavaScript / jquery将动态html模板打印到页面上

[英]Printing dynamic html templates onto page with JavaScript/jquery

I have this html template: 我有这个html模板:

<template id="photo-template">
    <div class="template-border">
        <p class="name"></p>
    </div>
</template>

I want to display multiple of these on the same page but change the name depending on some strings in a javascript array. 我想在同一页面上显示多个,但根据JavaScript数组中的某些字符串更改名称。 This is the code I have to display the templates: 这是我必须显示模板的代码:

for (var i = 0; i < 3; i++) {
    var tmpl = document.getElementById('photo-template').content.cloneNode(true);
    $("#content").append(tmpl);
    $(".name").text(javascript_array[i]);
}

The result should be 3 templates on the page each with a different name, but, for some reason, it prints the 3 templates only with the last name in the array. 结果应该是页面上的3个模板,每个模板都使用不同的名称,但是由于某种原因,它仅打印数组中姓氏的3个模板。 For example if I had an array {"Alex","John","Thomas"} all 3 templates would have Thomas as the name. 例如,如果我有一个数组{“ Alex”,“ John”,“ Thomas”},则所有3个模板都将Thomas命名。 If I did 如果我做了

for (var i = 0; i < 2; i++) {...}

all 3 templates would have the name John. 所有3个模板的名称均为John。 So, how do I make then appear with the different names? 那么,如何使它们以不同的名称出现?

When you do $(".name").text() you target all the elements that have the .name class, so all your templates. 当您执行$(".name").text()您将定位所有具有.name类的元素,因此将所有模板定位为目标。 You need to be more specific with your selector to select only the template you just added. 您需要对选择器进行更具体的选择,以仅选择刚添加的模板。

You could do : 你可以做:

for (var i = 0; i < 3; i++) {
    var tmpl = document.getElementById('photo-template').content.cloneNode(true);
    $("#content").append(tmpl);
    $(".name").eq(i).text(javascript_array[i]);
}

Just by adding .eq(i) you'll select the current template you're working with. 只需添加.eq(i) ,即可选择正在使用的当前模板。 ( https://api.jquery.com/eq/ ) https://api.jquery.com/eq/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM