简体   繁体   中英

Printing dynamic html templates onto page with JavaScript/jquery

I have this html template:

<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. 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. For example if I had an array {"Alex","John","Thomas"} all 3 templates would have Thomas as the name. If I did

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

all 3 templates would have the name 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. 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. ( https://api.jquery.com/eq/ )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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