为什么不能下划线.js读取数据?

时间:2015-09-15 09:29:43

标签: javascript underscore.js underscore.js-templating

这是我的js代码:
task.js

var result = [{user: 'a'}, {'user': b}]
$('#cc_test').html(_.template($('#tpl_vgroup_row_test').html(), result)) 

template.html

<div id='cc_test'></div>
<script type="text/template" id="tpl_vgroup_row_test">
  <%= result %>
</script>  

但Chrome控制台告诉我这个:

Uncaught ReferenceError: result is not defined  

出了什么问题?

1 个答案:

答案 0 :(得分:1)

尝试将对象传递给_.template而不是仅传递一个值,就像这样

&#13;
&#13;
var result = [{user: 'a'}, {'user': 'b'}]
$('#cc_test').html(_.template($('#tpl_vgroup_row_test').html(), {result: result})) 
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

<div id='cc_test'></div>
<script type="text/template" id="tpl_vgroup_row_test">
  <%= result %>
  <%= result[0].user %>
  <%= result[1].user %> 
</script>
&#13;
&#13;
&#13;