【发布时间】:2013-04-03 23:18:45
【问题描述】:
根据 Nicholas Zaka 的“可维护的 JavaScript”一书,我知道在我的页面中放置一个小型 HTML 模板的最佳方法是添加如下内容:
<script type="text/x-templates" class="templates">
<div class="template1"> ... </div>
<div class="template2"> ... </div>
...
</script>
我更喜欢这种方法,而不是将我的模板放在 <body> 中并使用 css 隐藏它们,因为这些仍然会显示在像 dillo 这样的浏览器中。
我目前使用 jQuery 获取它们的方式是这样的:
var $templates = $('<div/>').append($('.templates').text()).children();
我尝试过但不起作用的事情是:
var $templates = $('.templates');
var $templates = $($('.templates').text());
var $templates = $($('.templates').html());
我现在的解决方案有效,但对我来说似乎不是很优雅。最好的方法是什么?
【问题讨论】:
-
你应该在 Google jquery html 模板中尝试过这 3 个关键字 ---> stephenwalther.com/archive/2010/11/30/…
-
他可能更喜欢扮演自己的角色。
-
是的,我想尽可能避免使用额外的依赖项,但感谢您的链接。
-
使用
html()而不是text()。如果你有多个,$('.templates').html()只会从该类的第一个返回 html
标签: jquery html client-side-templating