2017-06-16 80 views
0

考慮下面的代碼片段我想:如何在字符串中使用運算符三元組?

<script> 
    for (var key in photoList) { 
     if(key == photoList[key].id) { 
      var res = `<li id="thumbnail-`+key+`"> 
          <div class="thumbnail `+(product.photo == photoList[key].id)+` ? 'thumbnail-main' : ''"> 
           ... 
          </div> 
         </li>`; 
     } 
    } 
</script> 

我嘗試這樣,但它沒有工作?我該怎麼做?

+1

的可能的複製[?如何寫用jQuery這個三元操作符(https://stackoverflow.com/questions/6595585/how-to-write-這三元操作符與jquery) –

+0

https://stackoverflow.com/questions/6259982/how-do-you-use-the-conditional-operator-in-javascript – user7929528

+0

Theres a'before the?使它成爲一個字符串 –

回答

7

當你圍成的墳墓標記(')的字符串,它允許對字符串連接插表達,稱爲template literal這在ES2015中是新的。您的三元運算符是的表達式,因此您可以在字符串插值中使用${expr}表示法來插入表達式。既然你已經使用模板文字,沒有理由做串聯,從而:

var res = `<li id="thumbnail-${key}"> 
      <div class="thumbnail ${product.photo == photoList[key].id ? 'thumbnail-main' : ''}> 
       ... 
      </div> 
      </li>`; 

任何你想用一個表達式的字符串連接,你可以使用插值。因此,而不是:

'1 + 1 = ' + (1 + 1) 

你可以這樣做:

`1 + 1 = ${1 + 1}` 

因爲1 + 1是一個表達式。

+0

似乎你可以幫助我。看看這個:https://stackoverflow.com/questions/44665670/how-can-i-solve-uncaught-syntaxerror-unexpected-identifier-in-string-javascript –

0

你在做就OK了,但缺少字符串連接

<script> 
for (var key in photoList) { 
    if(key == photoList[key].id) { 
     var res = `<li id="thumbnail-`+key+`"> 
         <div class="thumbnail `+(product.photo == photoList[key].id ? 'thumbnail-main' : '') + `"> 
          ... 
         </div> 
        </li>`; 
    } 
} 

0

它應該是:

<script> 
    for (var key in photoList) { 
     if(key == photoList[key].id) { 
      var res = '<li id="thumbnail-'+key+'"><div class="thumbnail ' + ((product.photo == photoList[key].id)+ ? 'thumbnail-main' : '') + "> 
           ... 
          </div> 
         </li>'; 
     } 
    } 
</script> 
+0

似乎你可以幫助我。看看這個:https://stackoverflow.com/questions/44665670/how-can-i-solve-uncaught-syntaxerror-unexpected-identifier-in-string-javascript –

0
for (var key in photoList) { 
    if (key === photoList[key].id) { 
    var res = ` 
     <li id="thumbnail-${key}"> 
     <div class="thumbnail ${ 
     (product.photo === photoList[key].id) ? 'thumbnail-main' : '' 
     }"> 
     ... 
     </div> 
     </li>`; 
    } 
}