【问题标题】:In .js.erb file only one condition is working在 .js.erb 文件中,只有一个条件有效
【发布时间】:2014-05-16 06:20:07
【问题描述】:

在 .js.erb 文件中,只有一个条件有效。

var price = <%= @price %> // assigned for substitution, dont take this a concern
<%- if @price.nil? %>
   alert("if");
  // JS code if true
<%- else %>
   alert("else");
  // JS code if false
<%- end %>

在检查控制台时

@price 中有以下任何一项。

  1. 0.00333333

else 内的警报仅起作用。如果我有@price=nil 警报不起作用。我在语法上做错了什么吗?

答案:

以下代码有效。

if (price == "") {
 alert("if"); 
}
else {
  alert("else");
}

【问题讨论】:

    标签: javascript jquery ruby-on-rails ajax ruby-on-rails-4


    【解决方案1】:

    因为如果您的价格为零,则生成以下代码

    var price = nil // assigned for substitution, dont take this a concern
    

    这会给你错误nil is not defined

    所以不要回显nil值回显false or 0

    注意:不要忘记在javascript中放置分号

    var price = <%= @price %>;
    

    已编辑

    他们是你的两个案例

    案例1:如果@price 为nil。所以你生成的输出将是这样的

        var price = nil // assigned for substitution, dont take this a concern
        // above line will give you error nil is not defined
        alert("if")
    

    案例 2:如果@price 为 22。那么您生成的输出将是这样的

        var price = 22 // assigned for substitution, dont take this a concern
        alert("else")
        // will work perfectly fine.
    

    【讨论】:

    • 听不懂你想说什么?
    • 检查 如果价格为零则打印什么
    • 因此您的输出将与我在回答中给出的相同。所以它们在 javascript 中一点也不像 nil
    • 您的回答类似。更新答案
    猜你喜欢
    • 1970-01-01
    • 2010-10-10
    • 2022-08-12
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多