【问题标题】:Ternary Operator in jQuery statementjQuery 语句中的三元运算符
【发布时间】:2016-04-25 03:01:30
【问题描述】:

我是 Javascript、CSS、HTML 和 jQuery 的新手,遇到了这行使用 condition ? if true : if false 语句的代码,我正在努力理解它。等效的if() {} else {} 语句是什么样的?这是代码行:

$('.app-container').css('background', this.background ? `url(${this.background.get('Href')})` : `url(${DefaultImage.Background}`);

感谢您的任何解释:)

【问题讨论】:

  • 不知道你的例子中所有额外的单代码引号是怎么回事:)
  • 我只能猜测反引号表示ES6 template strings,否则它们是其他一些未知JS框架的一部分。

标签: javascript jquery css if-statement ternary-operator


【解决方案1】:

如果您正在寻找使用传统 if-else 的确切外观:

if (this.background)
    $('.app-container').css('background', `url(${this.background.get('Href')})`);
else
    $('.app-container').css('background',`url(${DefaultImage.Background}`);

在 javascript 中,三元运算符遵循这个基本前提:

(condition) ? (what will happen if condition evaluates to true) : (what will happen if condition evaluates to false)

有时它们可​​能难以破译,但在正确的情况下(例如这种情况),它们可以让您免于编写“额外”代码。

【讨论】:

    【解决方案2】:

    您需要将传递给url() 的第二个参数扩展为ifelse,因为它首先被评估:

    if (this.background)
        bgurl = `url(${this.background.get('Href')})`
    else 
        bgurl = `url(${DefaultImage.Background})`
    
    $('.app-container').css('background', bgurl);
    

    【讨论】:

      猜你喜欢
      • 2017-10-20
      • 1970-01-01
      • 2016-06-28
      • 1970-01-01
      • 1970-01-01
      • 2015-10-13
      • 2011-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多