简体   繁体   English

如何在页面中添加HTML模板?

[英]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. 我一直在寻找,我看到了带有javascript和其他解决方案(例如Mustache)的模板标签。 Which approach would be better and more readable? 哪种方法更好并且更具可读性?

Not exactly sure what your asking but this would be very simple using pure javascript. 不完全确定您的要求是什么,但是使用纯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> 

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

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