最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Ternary Operator in jQuery statement - Stack Overflow

programmeradmin4浏览0评论

I'm new to Javascript, CSS, HTML, and jQuery, and came across this line of code that uses the condition ? if true : if false statement, and I'm trying to understand it. What would it's equivalent if() {} else {} statement look like? This is the line of code:

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

Thanks for any explanation :)

I'm new to Javascript, CSS, HTML, and jQuery, and came across this line of code that uses the condition ? if true : if false statement, and I'm trying to understand it. What would it's equivalent if() {} else {} statement look like? This is the line of code:

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

Thanks for any explanation :)

Share Improve this question asked Jan 19, 2016 at 15:05 keennskeenns 9034 gold badges15 silver badges26 bronze badges 2
  • Not sure what's with all the extra single code-quotes in your example though :) – iCollect.it Ltd Commented Jan 19, 2016 at 15:08
  • I can only guess that the backticks indicate ES6 template strings, or else they're part of some other unknown JS framework. – Blazemonger Commented Jan 19, 2016 at 15:27
Add a ment  | 

2 Answers 2

Reset to default 3

You need to expand the second parameter that was passed to url() to an if, else as that is evaluated first:

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 (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:

(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.

发布评论

评论列表(0)

  1. 暂无评论