jQuery text() 的条件语句(三元)
jQuery Conditional Statement (Ternary) for text()
我正在尝试将元素 (promo-footer) 的文本值设置为变量 (footerVar) 的内容,如果它不是空字符串 ''。
$('.promo-footer').text(footerVar == '' ? 'no' : footerVar);
有效,仅显示页脚文本(如果存在)且变量为空字符串 '' 则显示 "no"...
我的问题是 - 为什么这样做有效?我认为如果等式的计算结果为 true
?
,问号后的第一件事就会发生
x = (1 < 2) ? true : false;
当 footerVar
为空字符串时,此 footerVar == ''
为真。但在您的情况下,它是一个非空字符串。所以它的计算结果为 false
并且表达式属于 false 部分被返回。即] :
之后
以下示例将澄清您对三元运算符用法的疑问。
var x = (true) ? 10 : 20;
console.log(x); //10;
var x = (false) ? 10 : 20;
console.log(x); //20;
这是 ternary operator、
的语法
(condition)
? expression has to be returned when condition evaluates to true
: expression has to be returned when condition evaluates to false
你说得对,因为如果 footerVar === ' ',则条件为真。(页脚为空)并且它是 return 第一个语句。如果 footerVar 不为空,则条件为假,它 return 第二条语句。
它按应有的方式工作。
var promotionObj = {};
promotionObj.footer_text = "foot test";
// This works, says "foot test". Why??
$('.promo-footer').text(promotionObj.footer_text == '' ? 'no' : promotionObj.footer_text);
// This says "no":
$('.promo-footer').text(promotionObj.footer_text == '' ? promotionObj.footer_text : 'no');
现在考虑上面的代码,它来自您发布的 fiddle。
第一个说 "foo test" 因为 promotionObj.footer_text 不是空字符串。代码的第二部分说 "no" 因为您交换了表达式的排列,其中变量的值: promotionObj.footer_text 如果它为空,则仅用作页脚文本,在这种情况下它不为空,因此 "no" 将代替它显示。
考虑一下。
var arg = 5;
var result = arg > 10 ? arg : 0; // result contains 0
var result = arg > 10 ? 0 : arg // result contains 5 which is the value of arg
希望解释清楚。
我正在尝试将元素 (promo-footer) 的文本值设置为变量 (footerVar) 的内容,如果它不是空字符串 ''。
$('.promo-footer').text(footerVar == '' ? 'no' : footerVar);
有效,仅显示页脚文本(如果存在)且变量为空字符串 '' 则显示 "no"...
我的问题是 - 为什么这样做有效?我认为如果等式的计算结果为 true
?
x = (1 < 2) ? true : false;
当 footerVar
为空字符串时,此 footerVar == ''
为真。但在您的情况下,它是一个非空字符串。所以它的计算结果为 false
并且表达式属于 false 部分被返回。即] :
以下示例将澄清您对三元运算符用法的疑问。
var x = (true) ? 10 : 20;
console.log(x); //10;
var x = (false) ? 10 : 20;
console.log(x); //20;
这是 ternary operator、
的语法(condition)
? expression has to be returned when condition evaluates to true
: expression has to be returned when condition evaluates to false
你说得对,因为如果 footerVar === ' ',则条件为真。(页脚为空)并且它是 return 第一个语句。如果 footerVar 不为空,则条件为假,它 return 第二条语句。
它按应有的方式工作。
var promotionObj = {};
promotionObj.footer_text = "foot test";
// This works, says "foot test". Why??
$('.promo-footer').text(promotionObj.footer_text == '' ? 'no' : promotionObj.footer_text);
// This says "no":
$('.promo-footer').text(promotionObj.footer_text == '' ? promotionObj.footer_text : 'no');
现在考虑上面的代码,它来自您发布的 fiddle。 第一个说 "foo test" 因为 promotionObj.footer_text 不是空字符串。代码的第二部分说 "no" 因为您交换了表达式的排列,其中变量的值: promotionObj.footer_text 如果它为空,则仅用作页脚文本,在这种情况下它不为空,因此 "no" 将代替它显示。
考虑一下。
var arg = 5;
var result = arg > 10 ? arg : 0; // result contains 0
var result = arg > 10 ? 0 : arg // result contains 5 which is the value of arg
希望解释清楚。