简体   繁体   English

jQuery语句中的三元运算符

[英]Ternary Operator in jQuery statement

I'm new to Javascript, CSS, HTML, and jQuery, and came across this line of code that uses the condition ? if true : if false 我是Java,CSS,HTML和jQuery的新手,遇到了使用condition ? if true : if false condition ? if true : if false statement, and I'm trying to understand it. condition ? if true : if false ,则我试图理解它。 What would it's equivalent if() {} else {} statement look like? if() {} else {}语句看起来像什么? This is the line of code: 这是代码行:

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

Thanks for any explanation :) 感谢您的解释:)

You need to expand the second parameter that was passed to url() to an if , else as that is evaluated first: 您需要将传递给url()的第二个参数扩展为ifelse将首先进行评估:

if (this.background)
    bgurl = `url(${this.background.get('Href')})`
else 
    bgurl = `url(${DefaultImage.Background})`

$('.app-container').css('background', bgurl);

If you're looking for exactly what this would look like with a traditional if-else : 如果您正在寻找传统if-else外观, if-else

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

In javascript the ternary operator follows this basic premise: 在javascript中,三元运算符遵循以下基本前提:

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

Sometimes they can be difficult to decipher but in the right situation (like this one) they can save you from writing 'extra' code. 有时,它们可能难以解读,但在正确的情况下(如这种情况),它们可以使您免于编写“额外的”代码。

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

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