[英]Using IF statements in Underscore.js/Backbone.js templates
我收到一個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-object被正確解碼,那么檢查(price)
或(price != null)
應該沒問題。
不應該是==
(在這種情況下!==
)進行比較
<% if (price !== null) { %>
<div class="subtitle">$<%= price %></div>
<% } %>
例如,看看這個Jsbin.com線的警告
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.