我正在努力学习Handlebars.js (第一个小时)&似乎遇到了一个初始问题(它不起作用)。
这是我的html:
<!doctype html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.js"></script>
<script src="js/handlebars-v4.0.5.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<p>Hi!</p>
<script id="some-template" type="text/x-handlebars-template">
<table>
<thead>
<th>Username</th>
<th>Real Name</th>
<th>Email</th>
</thead>
<tbody>
{{#users}}
<tr>
<td>{{username}}</td>
<td>{{firstName}} {{lastName}}</td>
<td>{{email}}</td>
</tr>
{{/users}}
</tbody>
</table>
</script>
</body>
</html>这是我的main.js:
$(document).ready(function() {
console.log("I'm Here!");
var source = $("#some-template").html();
var template = Handlebars.compile(source);
var data = {
users: [{
username: "alan",
firstName: "Alan",
lastName: "Johnson",
email: "alan@test.com"
}, {
username: "allison",
firstName: "Allison",
lastName: "House",
email: "allison@test.com"
}, {
username: "ryan",
firstName: "Ryan",
lastName: "Carson",
email: "ryan@test.com"
}]
};
$("#content-placeholder").html(template(data));
});我看到了控制台日志,但是这个表根本没有被写入。这里没有控制台错误消息&我有点不知道问题在哪里。
希望不是疲劳引起的明显的错误.
发布于 2016-01-09 01:01:56
要使您的代码像您所拥有的那样工作,您需要在文档中定义一个与#content-placeholder匹配的HTML元素,这样$("#content-placeholder").html(template(data));就有了放置呈现模板的位置。
可以通过将它添加到HTML中来解决这个问题,如下所示:
<!doctype html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.js"></script>
<script src="js/handlebars-v4.0.5.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<p>Hi!</p>
<script id="some-template" type="text/x-handlebars-template">
<table>
<thead>
<th>Username</th>
<th>Real Name</th>
<th>Email</th>
</thead>
<tbody>
{{#users}}
<tr>
<td>{{username}}</td>
<td>{{firstName}} {{lastName}}</td>
<td>{{email}}</td>
</tr>
{{/users}}
</tbody>
</table>
</script>
<!-- Add this line -->
<div id="content-placeholder"></div>
</body>
</html>发布于 2016-01-09 00:33:26
我改变了
$("#content-placeholder").html(template(data));
至
$('body').append(template(data));
&我得到了想要的输出。
https://stackoverflow.com/questions/34687910
复制相似问题