Jquery 如何从外部访问Mustache HTML模板<;脚本/>;
我使用它来呈现HTML站点的不同重复部分。到目前为止,我将每个模板都放在Jquery 如何从外部访问Mustache HTML模板<;脚本/>;,jquery,mustache,Jquery,Mustache,我使用它来呈现HTML站点的不同重复部分。到目前为止,我将每个模板都放在中,并通过jQueryshtml()方法访问其内容: <script type="text/html" id="html-script"> <!-- ... --> </script> <script type="text/javascript"> $('script[type="text/html"]').each(function() { var $thi
中,并通过jQueryshtml()
方法访问其内容:
<script type="text/html" id="html-script">
<!-- ... -->
</script>
<script type="text/javascript">
$('script[type="text/html"]').each(function() {
var $this = $(this);
templates[$this.attr('title')] = $this.html();
});
</script>
$('script[type=“text/html”]”)。每个(函数(){
var$this=$(this);
模板[$this.attr('title')]=$this.html();
});
现在,我想将每个模板放在其自己的文件中,并将其包括如下:
<script type="text/html" id="html-script" src="template.html"></script>
这不起作用,所以我的问题是
$.get()
模板,我会非常感激。虽然对于
元素的src
可以是什么有点模糊,但它确实这么说“资源是给定类型的脚本资源,如果该类型标识脚本语言,并且该资源符合该语言规范的要求。”实际上,这意味着浏览器将只加载javascript,而您无法与以这种方式加载的HTML文档交互
我会重新思考您试图解决问题的方式。这是一种异步加载从以下站点窃取的模板文件的解决方案:
[]
(显然,修改tpl
目录以满足您的需要)
您也可以使用类似(我的首选方法)的方法来执行此操作。此解决方案使用jQuery holdReady方法向onReady事件添加延迟。请注意,必须在加载资源脚本之前包含jQuery脚本
<script src="jquery.min.js"></script>
<script src="mustache.min.js"></script>
<script id="template1" type="x-tmpl-mustache" src="template1.html"></script>
<script id="template2" type="x-tmpl-mustache" src="template2.html"></script>
<script type="text/javascript">
$('script[type="x-tmpl-mustache"]').each(function(idx, templateSource) {
$.holdReady(true);
$.get(templateSource.src, function(template) {
templateSource.text = template;
$.holdReady(false);
});
});
$(document).ready(function() {
Console.log("All templates loaded.");
});
</script>
$('script[type=“x-tmpl-mustache”]”)。每个(函数(idx,templateSource){
$.holdReady(真);
$.get(templateSource.src,函数(模板){
templateSource.text=模板;
$.holdReady(假);
});
});
$(文档).ready(函数(){
log(“加载了所有模板”);
});
你能解释一下延迟之间的魔力是如何发生的吗?push()和//做一些令人惊奇的事情吗?:)…我的意思是,视图对象在哪里?
<script src="jquery.min.js"></script>
<script src="mustache.min.js"></script>
<script id="template1" type="x-tmpl-mustache" src="template1.html"></script>
<script id="template2" type="x-tmpl-mustache" src="template2.html"></script>
<script type="text/javascript">
$('script[type="x-tmpl-mustache"]').each(function(idx, templateSource) {
$.holdReady(true);
$.get(templateSource.src, function(template) {
templateSource.text = template;
$.holdReady(false);
});
});
$(document).ready(function() {
Console.log("All templates loaded.");
});
</script>