gpt4 book ai didi

javascript - underscore.js:1461 Uncaught ReferenceError: 用户未定义

转载 作者:行者123 更新时间:2023-12-01 04:02:32 25 4
gpt4 key购买 nike

我是backbone.js 和 underscore.js 的新手。我正在尝试创建一个示例应用程序。

我的代码是:

<script type="text/template" id="user-list-template">
<table class = "table striped">
<thead>
<tr>
<th>User Name</th>
<th>Age</th>
<th>Location</th>
<th></th>
</tr>
</thead>
<tbody>
<% _.each(users, function(user){%>
<tr>
<td><% user.get('sUserName') %></td>
<td><% user.get('iAge') %></td>
<td><% user.get('sLocation') %></td>
<td></td>
</tr>
<% }) %>
</tbody>
</table>
</script>
var UserList = Backbone.View.extend({
el: '.page',
render: function() {
var that = this;
var users = new Users;
users.fetch({
success: function(users) {
alert("REST Service call was success");
var template = _.template($('#user-list-template').html(), { users: users.models });
that.$el.html(template);
console.log('The content rendered here...');
}
})

}
});

但我遇到了这个异常:

Uncaught ReferenceError: users is not defined
at HTMLDivElement.eval (eval at m.template (underscore.js:1454), <anonymous>:6:9)
at HTMLDivElement.c (underscore.js:1461)
at n.access (jquery.min.js:3)
at n.fn.init.html (jquery.min.js:3)
at success ((index):64)
at Object.t.success (backbone.js:1051)
at j (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at x (jquery.min.js:4)
at XMLHttpRequest.b (jquery.min.js:4)

最佳答案

正如所指出的,您应该使用 <%= %> (或者更好的是 <%- %> 被转义),但你的主要问题看起来是你调用模板的方式。

_.template()下划线中的函数又返回一个可重用的函数,您可以使用不同的数据调用该函数。

var users = new Backbone.Collection([
{sUserName: 'Alice', iAge: 35, sLocation: 'London'},
{sUserName: 'Bob', iAge: 5, sLocation: 'Buenos Aires'}
]);
var template = _.template($('#user-list-template').html());
$('#result').html(template({users: users.models}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
<script type="text/template" id="user-list-template">
<table class = "table striped">
<thead>
<tr>
<th>User Name</th>
<th>Age</th>
<th>Location</th>
<th></th>
</tr>
</thead>
<tbody>
<% _.each(users, function(user){%>
<tr>
<td><%- user.get('sUserName') %></td>
<td><%- user.get('iAge') %></td>
<td><%- user.get('sLocation') %></td>
<td></td>
</tr>
<% }) %>
</tbody>
</table>
</script>
<div id="result"/>

关于javascript - underscore.js:1461 Uncaught ReferenceError: 用户未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42088607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com