定义要使用JQuery追加的HTML模板 [英] Defining a HTML template to append using JQuery
问题描述
我有一个我正在循环的数组。每次条件成立时,我都想将下面的 HTML
代码的副本附加到带有一些值的容器元素。
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 values.
我可以在哪里以智能方式重复使用此HTML?
Where can I put this HTML to re-use in a smart way?
<a href="#" class="list-group-item">
<div class="image">
<img src="" />
</div>
<p class="list-group-item-text"></p>
</a>
JQuery
$('.search').keyup(function() {
$('.list-items').html(null);
$.each(items, function(index) {
// APPENDING CODE HERE
});
});
推荐答案
您可以决定使用模板引擎您的项目,例如:
You could decide to make use of a templating engine in your project, such as:
- mustache
- underscore.js
- handlebars
如果您不想包含其他库,John Resig提供 jQuery解决方案,类似于下面的那个。
If you don't want to include another library, John Resig offers a jQuery solution, similar to the one below.
浏览器和屏幕阅读器忽略无法识别的脚本类型:
Browsers and screen readers ignore unrecognized script types:
<script id="hidden-template" type="text/x-custom-template">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
</script>
使用jQuery,根据模板添加行将类似于:
Using jQuery, adding rows based on the template would resemble:
var template = $('#hidden-template').html();
$('button.addRow').click(function() {
$('#targetTable').append(template);
});
这篇关于定义要使用JQuery追加的HTML模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!