我收到一个JSON对象,其中一个值为null
。JSON看起来像:
[{"id":"1096","price":null,
现在,它正在使用以下代码向网页输出一个NULL
字符串(我使用的是Backbone.js/Underscore.js中的模板引擎)
<div class="subtitle">$<%= price %></div>
因为如果没有返回price
,我想隐藏整个div
,所以我添加了if
语句:
<% if (price) { %>
<div class="subtitle">$<%= price %></div>
<% } %>
然而,它似乎仍然输出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>
<% } %>
我怀疑这与在Underscore.js的模板中使用if
语句有关
嗯,你不想要(没有感叹号)吗
<% if (price) { %>
<div class="subtitle">$<%= price %></div>
<% } %>
因为你现在说如果没有价格,那么显示价格。。。这毫无意义。
null
不是undefined
!
如果json对象被正确解码,那么检查(price)
或(price != null)
应该没问题。
它不应该是比较的==
(在这种情况下是!==
)吗
<% if (price !== null) { %>
<div class="subtitle">$<%= price %></div>
<% } %>
例如,查看Jsbin.com的行的警告