【问题标题】:Using IF statements in Underscore.js/Backbone.js templates在 Underscore.js/Backbone.js 模板中使用 IF 语句
【发布时间】:2012-07-12 13:58:01
【问题描述】:

我收到一个 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 语句有关

【问题讨论】:

  • 您确定要从数组中传入单个对象吗?我们可以查看您的整个下划线模板以及您传入的值吗?

标签: javascript jquery backbone.js underscore.js


【解决方案1】:

呃,你不想要(没有感叹号)

<% if (price) { %>
    <div class="subtitle">$<%= price %></div>
<% } %>

因为你现在说如果没有价格然后显示价格......这是没有意义的。

【讨论】:

  • 是的,你是对的!我改成if(price),还是不行。我怀疑这与在 underscore.js 的模板中使用 if 语句有关
【解决方案2】:

null 不是undefined

如果您的 json-object 被正确解码,那么检查 (price)(price != null) 应该没问题。

【讨论】:

  • console.log(price) 给了我一个object。但是if(!price) 不起作用! :-/ 我正在使用backbone.js 的this.myCollectionName.fetch() 来获取JSON 对象并对其进行解码。
  • 好吧,这很明显。对象总是真实的。 console.log(price) 应该给你null
【解决方案3】:

不应该是==(本例为!==)进行比较

<% if (price !== null) { %>
    <div class="subtitle">$<%= price %></div>
<% } %>

例如查看Jsbin.com 行的警告

【讨论】:

    猜你喜欢
    • 2011-11-06
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    相关资源
    最近更新 更多