要有遥不可及的梦想,也要有脚踏实地的本事。----------- Grapefruit.Banuit Gang(香柚帮)
模板字符串:
模板字符串相当于加强版的字符串,用反引号 `,除了作为普通字符串,还可以用来定义多行字符串,还可以在字符串中加入变量和表达式。
基本用法:
普通字符串
let string = `Hello'\n'world`;
console.log(string);
// "Hello'
// 'world"
多行字符串:
let string1 = `Hey,
can you stop angry now?`;
console.log(string1);
// Hey,
// can you stop angry now?
字符串插入变量和表达式。
变量名写在 ${} 中,${} 中可以放入 JavaScript 表达式。
let name = "Henry";
let age = 23
let info = `My Name is ${name},I am ${age+1} years old next year.`
console.log(info);
// My Name is Henry,I am 24 years old next year.
模板字符串中还可以调用函数:
function makeUppercase(word){
return word.toUpperCase();
}
let template = `${makeUppercase('Hello')}!`;
下面可以用一段代码来理解一下具体的使用:
<body>
<div class="container">
<div id="template">
</div>
</div>
</body>
let name = "Henry";
let age = 23
function makeUppercase(word){
return word.toUpperCase();
}
let template =
`
<h1>${makeUppercase('Hello')}, ${name}!</h1>
<p>${age + 1}</p>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
`;
document.getElementById('template').innerHTML = template;
好了,就是这些了,希望有用吧!!!