text()的jQuery条件语句(三元)



如果元素(promo-footer)不是空字符串",我将尝试将其文本值设置为变量(footerVar)的内容。

$('.promo-footer').text(footerVar == '' ? 'no' : footerVar);

这很有效,并且只显示页脚文本(如果存在),并且变量是空字符串",则显示"no"。。。

我的问题是,为什么这样做?我想,如果方程的值为true,那么问号之后的第一件事会发生吗?

x = (1 < 2) ? true : false;

它在这里发挥作用:https://jsfiddle.net/xfzgaLq6/

它以应有的方式工作。

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

我希望解释清楚。

footerVar为空字符串时,此footerVar == ''为true。但在您的情况下,它是一个非空字符串。因此它的求值为false,并且表达式属于返回的伪部分。即]在: 之后

以下示例将澄清您对三元运算符用法的怀疑。

var x = (true) ? 10 : 20;
console.log(x); //10;
var x = (false) ? 10 : 20;
console.log(x); //20;

这是三元运算符的语法

(condition) 
  ? expression has to be returned when condition evaluates to true
  : expression has to be returned when condition evaluates to false

你说得对,因为如果footerVar==='',那么条件为true。(页脚为空),并返回第一条语句。如果footerVar不为空,则条件为false,并返回第二条语句。

最新更新