下划线把我难住了!在我的代码中,一切都适用于在 $.when 之后获取数据。console.log(帖子);有效,但是当我尝试将其传递给模板并参考时
<h1><%=posts.id %></h1>
我在线收到“未捕获的 ReferenceError:未定义帖子”
$("#target").html(_.template(template,posts));
这是整个页面
<!DOCTYPE html>
<html>
<head>
<script src="js/api.js"></script>
<link href="css/styles.css" media="" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="target"></div>
<!-- BEGIN: Underscore Template Definition. -->
<script type="text/template" id="template">
<h1><%=posts.id %></h1>
</script>
<!-- END: Underscore Template Definition. -->
<!-- Include and run scripts. -->
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/underscore.js"></script>
<script type="text/javascript">
$.when(results).done(function(posts){
var template = $("#template").html();
console.log(posts);
$("#target").html(_.template(template,posts)
);
});
</script>
</body>
[Object]
0: Object
created_at: "2013-04"
id: "444556663333"
num_comments: 1
num_likes: 0
text: "<p>dfgg</p>"
title: "title1"
updated_at: "2013-04"
user: Object
first_name: "bob"
id: "43633"
last_name: "ddd"
****已更新* ** * ** 感谢大家,我的模板可以正常工作。_.each 循环遍历对象数组并从 API 填充 HTML 块和数据。现在,我需要做的是弹出一个包含特定帖子内容的模式。我正在为我的 .click 事件而苦苦挣扎。所有不同的模态都填充了正确的数据(隐藏时,引导模态),但是当我单击它们相应的 div 时,我不确定如何引用它们。我总是得到第一篇文章的内容。
$(".datachunk").click(function (){
$("#myModal").modal();
});
.datachunk 指的是您点击的当前 div.datachunk。这是我的模板:
<!-- BEGIN: Underscore Template Definition. -->
<script type="text/template" id="template">
<% _.each(posts,function(post){ %>
<div class = "datachunk borderBottom">
<div class="openModall"><i class="icon-plus-sign-alt"></i> </div>
<h2><%= post.title %></h2>
<div class="postInfo">
<p><%= post.user.first_name %><%= post.user.last_name %></p><p>
<% var date=moment(post.created_at).format("M/DD/YYYY");%>
<%= date %></p>
</div>
</div> <!--datachunk-->
<% }) %>
<!--BEGIN Modal-->
<% _.each(posts,function(post){ %>
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria- labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<div class="datachunk">
<div class= "postInfo">
<h2><%= post.title %></h2>
<p><%= post.user.first_name %><%= post.user.last_name %></p>
</div>
</div>
</div> <!--end modal header-->
<div class="modal-body">
<p><%=post.text %></p>
</div>
</div>
<!--END Modal-->
<% }) %>
</script>
<!-- END: Underscore Template Definition. -->