简体   繁体   中英

How to add HTML templates in a page?

I made an template of a price box, and I want that every time that I click a button a new price box shows up in the page. Just a simple example for my template:

<div>
  <h1> Product: {productName} </h1>
</div>

And everytime that I click a button, I pass the name and this template will show in the page.

I was looking and I saw the template tag with javascript and another solutions like Mustache. Which approach would be better and more readable?

Not exactly sure what your asking but this would be very simple using pure javascript. Please see the following code snippet:

 function addProduct() { const productName = document.querySelector('#productName').value; productName ? document.querySelector('#products').innerHTML += ` <div><h1>Product: ${productName}</h1></div> ` : alert('Enter Product Name'); } document.querySelector('#add').addEventListener('click', () => addProduct()); 
 <input type="text" id="productName"> <button id="add">Add Product</button> <div id="products"></div> 

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