2017-08-11 101 views
1

我正在嘗試學習ES6的第一步,現在正面臨模板的一些問題。ES6模板給出語法錯誤

的JavaScript看起來像這樣:

"use strict" 

let name = 'John'; 

function makeUpperCase(word){ 
    return word.toUpperCase(); 
} 

let template = '<h1>${makeUpperCase('Hello')} ${name} Developer</h1><p>paragraph comes here</p>'; 

document.getElementById('template').innerHTML = template; 

好像不被讀取我的變量:

'<h1>${makeUpperCase('Hello')} ${name} Developer</h1><p>paragraph comes here</p>'; 

所以,當我加載頁面看到我的控制檯說未捕獲的SyntaxError的錯誤:意外標識

我的index.html就這麼簡單:

<html> 
<head> 
    <meta charset="utf-8"> 
    <title>Learning ES6</title> 
</head> 
<body>  
    <header> 
     <h1 id="heading">Learning ES6</h1> 
     <p>With Sidney de Sousa</p> 
    </header> 

    <div id="container"> 
     <div id="template"> 

     </div> 
    </div> 
    <script src="src/main.js"></script> 
</body> 
</html> 

我應該看到一個標題說:HELLO John Developer。

希望你能幫助

+3

模板使用反引號'\''定義模板,讓你的代碼是:'\'

$ {makeUpperCase( '你好')} $ {name}的開發者

段落來到這裏

';' – Joe

回答

4

您正在使用單引號',因此它被解釋爲一個字符串。 ( - 這裏的第一'匹配與開口單引號 - 而且,當函數用於值'HELLO'字符串被解剖。因此HELLO被視爲在JavaScript變量,這是沒有定義)

你應該是使用反勾'這樣

let template = `<h1>${makeUpperCase('Hello')} ${name} Developer</h1><p>paragraph comes here</p>`; 
+1

完全不知道那個細節。我現在使用後面的勾號,它工作。 – Ragmah

0

你確定你使用的是反引號(`),而不是常規引號(')?

這裏是例子:

const str = `Hi, my name is ${userName}`; 

退房this link有關ES6模板文字細節。