我正在尝试使用Jquery在我的页面中使用把手模板。它是一个带有静态数据的简单页面,脚本标签中的模板。这是我的html,问题是Jquery没有加载我的脚本标签,其中包含我的模板,
var source = $('#tasks-template')。html();
源是未定义的,为什么这个未定义?
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.rc.1.min.js" />
<script id="tasks-template" type="text/x-handlebars-template">
<ul>
{{#tasks}}
<li>
<span>{{name}}</span> <span>{{count}}</span>
</li>
{{/tasks}}
</ul>
</script>
<script>
function replaceContent() {
var tasks = [{
name: 'A',
count: 9
}, {
name: 'B',
count: 10
}]
console.log(tasks);
var source = $('#tasks-template').html();
console.log("template src " + source)
var template = Handlebars.compile(source);
$('#content-placeholder').html(template(tasks));
}
replaceContent();
</script>
</head>
<body>
<div id="content-placeholder">
some content
</div>
</body>
</html>
链接
我想知道如何从内联脚本加载模板
这是html
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.rc.1.min.js" />
</head>
<body>
<script id="templateA" type="text/template">
<ul>
{{#tasks}}
<li>
<span>{{name}}</span> <span>{{count}}</span>
</li>
{{/tasks}}
</ul>
</script>
<script id="templateB" type="text/template">
<ul>
{{#tasks}}
<li>
<span>{{name}}</span> <span>{{count}}</span>
</li>
{{/tasks}}
</ul>
</script>
<script>
alert($('#templateA').html());
alert($('#templateB').html());
</script>
<div id="content-placeholder">
some content
</div>
</body>
</html>
链接
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.rc.1.min.js"></script>
</head>
<body>
<script id="templateA" type="text/template">
<ul>
{{#tasks}}
<li>
<span>{{name}}</span> <span>{{count}}</span>
</li>
{{/tasks}}
</ul>
</script>
<script id="templateB" type="text/template">
<ul>
{{#tasks}}
<li>
<span>{{name}}</span> <span>{{count}}</span>
</li>
{{/tasks}}
</ul>
</script>
<script>
alert($('#templateA').html());
alert($('#templateB').html());
</script>
<div id="content-placeholder">
some content
</div>
</body>
</html>
xN3Z5xei8S5EJqu P =预览
templateA导致未定义,但是模板B打印出来,为什么templateA未定义而templateB不是?
答案 0 :(得分:1)
语法的颜色应该为您提供线索:
需要使用script
关闭 </script>
代码,并且无法使用<script />
:
<script type="text/javascript" src="https://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.rc.1.min.js" />
...
{{/tasks}}
</ul>
</script> <-- This closes the above script that loads handlebars -->
变化:
<script type="text/javascript" src="https://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.rc.1.min.js" />
to(添加结束标记):
<script type="text/javascript" src="https://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.rc.1.min.js"></script>