mustache 模板 jquery 实现或怎么写
时间: 2024-04-30 18:22:00 浏览: 89
要使用 Mustache 模板和 jQuery 来动态生成 HTML,你需要在 HTML 页面中加载 jQuery 和 Mustache 库。你可以按照以下步骤来实现:
1. 在 HTML 页面中加载 jQuery 库和 Mustache 库:
```html
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/4.2.0/mustache.min.js"></script>
```
2. 创建 Mustache 模板:
```html
<script id="my-template" type="x-tmpl-mustache">
<div class="user">
<h2>{{name}}</h2>
<p>{{email}}</p>
</div>
</script>
```
3. 创建一个空的 div 元素来容纳生成的 HTML:
```html
<div id="my-container"></div>
```
4. 使用 jQuery 和 Mustache 库来渲染模板:
```javascript
$(document).ready(function() {
var data = {
name: "John Doe",
email: "john.doe@example.com"
};
var template = $('#my-template').html();
var html = Mustache.render(template, data);
$('#my-container').html(html);
});
```
这段代码将从 Mustache 模板创建 HTML,并将其插入到 ID 为 "my-container" 的 div 元素中。
阅读全文
相关推荐

















