简体   繁体   中英

How can I add condition in string javascript?

My javascript code like this :

var res =  `<td>
                if(product.photo == photo.name)
                <div class="box-check">
                    <span class="fa fa-check"></span>
                </div>
            </td>`;

I try like that. But seems it's wrong

How can I do it?

simplest (easiest) change I can think of is as follows:

var inner = product.photo == photo.name ? `<div class="box-check">
       <span class="fa fa-check"></span>
    </div>` : '';
var res =  `<td>${inner}</td>`;

alternatively

var res = `<td>${product.photo == photo.name?'<div class="box-check"><span class="fa fa-check"></span></div>':''}</td>`;

but you can NOT (easily) make the <div><span etc multiline in this case

I didn't try hard enough - nested template literals FTW :p

var res = `<td>${product.photo == photo.name?`<div class="box-check">
    <span class="fa fa-check"></span>
</div>`:''}</td>`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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