在.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
具有以下任何一项。
内部警报else
仅起作用。如果我有@price=nil
警报,则无法正常工作。我在语法上做错了什么吗?
回答:
以下代码有效。
if (price == "") {
alert("if");
}
else {
alert("else");
}
因为如果您的价格为零,则生成以下代码
var price = nil // assigned for substitution, dont take this a concern
这会给你错误 nil is not defined
因此,而不是回显nil
值echofalse or 0
注意:别忘了在JavaScript中加入分号
var price = <%= @price %>;
已编辑
他们是你的两个案例
情况1:如果@price为零。所以您生成的输出将是这样的
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.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句