Javascript 在下划线.js/Backbone.js模板中使用IF语句
我正在接收一个JSON对象,其中一个值为Javascript 在下划线.js/Backbone.js模板中使用IF语句,javascript,jquery,backbone.js,underscore.js,Javascript,Jquery,Backbone.js,Underscore.js,我正在接收一个JSON对象,其中一个值为null。JSON看起来像: [{"id":"1096","price":null, 现在,它正在使用以下代码向网页输出NULL字符串。(我正在使用Backbone.js/underline.js中的模板引擎) 但是,它似乎仍然输出div.subtitle。我做错了什么?我也尝试了以下方法,但都不起作用 <% if (typeof(price) != "undefined") { %> <div class="subtitle"
null
。JSON看起来像:
[{"id":"1096","price":null,
现在,它正在使用以下代码向网页输出NULL
字符串。(我正在使用Backbone.js/underline.js中的模板引擎)
但是,它似乎仍然输出div.subtitle
。我做错了什么?我也尝试了以下方法,但都不起作用
<% if (typeof(price) != "undefined") { %>
<div class="subtitle">$<%= price %></div>
<% } %>
<% if (price != null) { %>
<div class="subtitle">$<%= price %></div>
<% } %>
<% if (price != "null") { %>
<div class="subtitle">$<%= price %></div>
<% } %>
$
$
$
我怀疑这与在underline.js的模板中使用
if
语句有关null
不是未定义的
如果您的json对象被正确解码,那么检查(price)
或(price!=null)
就可以了。呃,您不想要(没有感叹号)
$
因为你现在说的是如果没有价格,那么就显示价格……这毫无意义。它不应该是一个用于比较的
=
(在本例中是!=
)吗
<% if (price !== null) { %>
<div class="subtitle">$<%= price %></div>
<% } %>
$
e、 g看这行的警告
控制台。log(price)
给我一个对象
。但是如果(!price)
不起作用!:-/我正在使用backbone.js的this.myCollectionName.fetch()
来获取JSON对象并对其进行解码。对象总是真实的console.log(price)
应该为您提供null
。是的,您是对的!我改为if(price)
,但它仍然不起作用。我怀疑这与在underline.js的模板中使用if
语句有关。您确定要从数组中传入单个对象吗?我们可以看到下划线模板的全部内容以及传递的值吗?
<% if (typeof(price) != "undefined") { %>
<div class="subtitle">$<%= price %></div>
<% } %>
<% if (price != null) { %>
<div class="subtitle">$<%= price %></div>
<% } %>
<% if (price != "null") { %>
<div class="subtitle">$<%= price %></div>
<% } %>
<% if (price) { %>
<div class="subtitle">$<%= price %></div>
<% } %>
<% if (price !== null) { %>
<div class="subtitle">$<%= price %></div>
<% } %>