【问题标题】:Why doesn't my ternary if statement evaluate for NULL?为什么我的三元 if 语句不评估为 NULL?
【发布时间】:2018-10-15 17:41:18
【问题描述】:

我正在尝试根据通过Ajax 函数从数据库返回的值更改附加按钮的文本。

 .append($('<td>').attr('id', "tdBookingStatus" + i).html(val.HasCustomerArrived === true ? "Checked in" : (val.HasCustomerArrived == null) ? " ": "Cancelled"))

但它对 NULL 不起作用,即使函数返回 NULL 但它不起作用我尝试了 =====! 但没有任何作用。

【问题讨论】:

  • f val.HasCustomerArrived 为“null”(字符串),那么您可以尝试这样的 .append($('').attr('id', "tdBookingStatus" + i)。 html(val.HasCustomerArrived ? "签到" : (val.HasCustomerArrived == "null") ? " ": "Cancelled"));
  • .html(val.HasCustomerArrived === true ,看起来你在这里错过了一个结束括号
  • 我认为我们需要更多的上下文。当我在this fiddle 中尝试时,它对值 true、false 和 null 按预期工作。
  • 哦,你说函数返回NULL,但你的代码检查null。这可能值得研究。

标签: javascript jquery html ternary-operator


【解决方案1】:

如果您正在考虑该值,您还需要检查 === ''。使用 null 是行不通的。

//for blank value
var test = '';
var res = test === true ? "Checked in" : (test === null || test === '') ? " ": "Cancelled"

console.log(res);

//for null value
var test = null;
var res = test === true ? "Checked in" : (test === null || test === '') ? " ": "Cancelled"

console.log(res);

//for true value
var test = true;
var res = test === true ? "Checked in" : (test === null || test === '') ? " ": "Cancelled"
console.log(res);

//for false value
var test = false;
var res = test === true ? "Checked in" : (test === null || test === '') ? " ": "Cancelled"
console.log(res);

【讨论】:

  • 如果 val.HasCustomerArrived 为“null”(字符串)会怎样
  • OP 在哪里提到这是一个字符串值? @thaveethugce
  • @AnkitAgarwal 谢谢,它适用于 '' 部分但不适用于 FALSE 部分,如果 val.HasCustomerArrived === false 那么它应该说已取消。
  • @Stacky 使用严格比较 === 检查我的更新答案
  • @Stacky 让我知道是否还有任何困惑。
猜你喜欢
相关资源
最近更新 更多
热门标签