我有一段从 Javascript 函数返回的 HTML 模板:
function getTemplate() {
return '<li id="element_idx_" class="elementChoice">' +
' <a href="#" onclick="_clickScript_" tabindex="27" title="_toolTip_">' +
' <span id="element_idx_title">_elementDisplayText_</span>' +
' <div class="elementIcon" id="element_idx_image"></div>' +
' <div class="actionIcon" id="element_idx_Icon"></div>' +
' </a>' +
'</li>';
}
子字符串 _idx_
、_clickScript_
等使用从 AJAX 调用检索的数据进行替换,使用的函数的定义类似于:
function interpolate(template, replacements) {
// * template is the HTML listed above
// * replacements is a JavaScript object, where the property names map to
// the substitution strings in the HTML template.
//
// E.g., { idx: 4, clickScript: function() { // click }, displayName: foo }
}
如您所见,某些项目在模板中被替换多次(即 _idx_
)。
Web 应用程序已经广泛使用了 jQuery,所以我想知道是否有一种更像 jQuery 风格的方法来实现这一点,也许使用 DOM,而不是依赖于字符串操作。
有什么想法吗?
最佳答案
John Resig 在博客中介绍了如何将此类模板放入脚本 block 中:
<script id='template1' type='text/html'>
<li id='element_idx' ...
...
</li>
</script>
浏览器不会尝试解释这些内容,但您可以获得文本:
var template = $('#template1').text();
这比将模板放入 Javascript 中要干净一些,但也并非没有问题。将模板与代码分离可能会有点痛苦或尴尬,具体取决于您的设置。
关于javascript - 如何在 jQuery 中将文本替换为 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3717724/