下划线传递对象作为参数

时间:2016-10-27 00:13:00

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

我使用Underscore.js创建模板。我想让模板中的每个按钮在与之关联的响应中传递。我可以使用响应ID执行此操作,使用:

import json

example_string = '{"totalCount": "1", "ID": "1029", "IP": "10.0.0.1"}'
result = json.loads(example_string)

print('totalCount:', result['totalCount'])
print('ID:', result['ID'])
print('IP:', result['IP'])

然后使用

<% _.each(responses, function(response){ %>
    <button class="btn btn-sm" onclick="citeResponse('<%= response._id %>')">Cite Response</button>
<% }); %>

根据ID查找响应。但是,当我确实知道我想要什么样的响应时,这会让我迭代一个数组。我试过了:

$.grep(responses, function(e){ return e._id == id; });

但是,<% _.each(responses, function(response){ %> <button class="btn btn-sm" onclick="citeResponse('<%= response %>')">Cite Response</button> <% }); %> 始终获得citeResponse。如何返回实际对象?

1 个答案:

答案 0 :(得分:0)

如果要通过参数传递的是JSON对象,则可以使用JSON.stringify(response)将其序列化为字符串。然后,在citeResponse函数中解析它,将其转换回JSON.parse(argument)的对象。

<% _.each(responses, function(response){ %>
<button class="btn btn-sm" onclick="citeResponse('<%= JSON.stringify(response) %>')">Cite Response</button>
function citeResponse(response) {
    response = JSON.parse(response);
    ...
}