繁体   English   中英

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

[英]jQuery Conditional Statement (Ternary) for text()

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

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

可行,并且仅显示页脚文本(如果存在),并且变量为空字符串”,则显示“否” ...

我的问题是-为什么这样做? 我以为如果方程式的计算结果为true问号之后就会发生第一件事?

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

它正在起作用: https : //jsfiddle.net/xfzgaLq6/

如果footerVar为空字符串, footerVar footerVar == ''为true。 但是在您的情况下,它是一个非空字符串。 因此它的计算结果为false并且返回了属于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。(footer为empty),它返回第一个语句。 如果footerVar不为空,则条件为false并返回第二条语句。

它按应有的方式工作。

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');

现在考虑上面发布的小提琴中的代码。 第一个说“ foo测试”,因为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

我希望解释清楚。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM