javascript 在 Underscore.js/Backbone.js 模板中使用 IF 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11453458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:17:34  来源:igfitidea点击:

Using IF statements in Underscore.js/Backbone.js templates

javascriptjquerybackbone.jsunderscore.js

提问by Nyxynyx

I am receiving a JSON object where one of the value is null. The JSON looks like:

我收到一个 JSON 对象,其中一个值是null. JSON 看起来像:

[{"id":"1096","price":null,

Right now, it is outputting a NULLstring to the webpage with the following code. (I am using the template engine in Backbone.js/Underscore.js)

现在,它正在NULL使用以下代码将字符串输出到网页。(我在 Backbone.js/Underscore.js 中使用模板引擎)

<div class="subtitle">$<%= price %></div>

Because I want to hide the entire divif no priceis returned, I added the ifstatements:

因为我想隐藏整个divif noprice返回,我添加了if语句:

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

However it seems to still output the div.subtitle. What am I doing wrong? I also tried the following but they did not work

但是它似乎仍然输出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>
<% } %>

I suspect this has to do with using ifstatements inside Underscore.js's templates

我怀疑这与使用ifUnderscore.js 模板中的语句有关

回答by CaffGeek

Uh, don't you want (no exclamation mark)

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

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

Because you are current saying if there is no price then display the price...which makes no sense.

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

回答by Christoph

nullis not undefined!

null不是undefined

If your json-object is correctly decoded, then checking (price)or (price != null)should be fine.

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

回答by Moritz Roessler

Shouldn't it be a ==(in this case !==) for comparison

不应该是==(在这种情况下!==)进行比较

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

e.g look at the warning of this Jsbin.comline

例如看看这个Jsbin.com行的警告