Defining a HTML template to append using JQuery

前端 未结 7 1016
死守一世寂寞
死守一世寂寞 2020-11-29 14:48

I have got an array which I am looping through. Every time a condition is true, I want to append a copy of the HTML code below to a container element with some

7条回答
  •  醉话见心
    2020-11-29 15:10

    Use HTML template instead!

    Since the accepted answer would represent overloading script method, I would like to suggest another which is, in my opinion, much cleaner and more secure due to XSS risks which come with overloading scripts.

    I made a demo to show you how to use it in an action and how to inject one template into another, edit and then add to the document DOM.

    example html

    
    

    example js

    // select
    var t = document.querySelector('#mytemplate');
    
    // set
    t.content.querySelector('img').src = 'demo.png';
    t.content.querySelector('p').textContent= 'demo text';
    
    // add to document DOM
    var clone = document.importNode(t.content, true); // where true means deep copy
    document.body.appendChild(clone);
    

    HTML <template>

    • +Its content is effectively inert until activated. Essentially, your markup is hidden DOM and does not render.

    • +Any content within a template won't have side effects. Scripts don't run, images don't load, audio doesn't play ...until the template is used.

    • +Content is considered not to be in the document. Using document.getElementById() or querySelector() in the main page won't return child nodes of a template.

    • +Templates can be placed anywhere inside of , , or and can contain any type of content which is allowed in those elements. Note that "anywhere" means that