1.模板字符串使用
案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>模板字符串</title>
<script src="../jquery.min.js"></script>
</head>
<body>
<div class="concent"></div>
</body>
<script>
let name = 'tangwei';
let age = 18;
//原来
let str = '这个人叫' + name + ',年龄是' + age;
//现在用字符串模板
let str1 = `这个人叫${name},年龄是${age}`;
console.log(str)
console.log(str1)
</script>
<script>
{
// 字符串中嵌入变量
let name = "Bob",
time = "today";
`Hello ${name}, how are you ${time}?`
}
</script>
<script>
$(function () {
$('.concent').html(`
<ul>
<li>first</li>
<li>second</li>
</ul>
`);
//trim方法可以消除多余的空格
$('.concent').html(`
<ul>
<li>first</li>
<li>second</li>
</ul>
`.trim());
})
</script>
<script>
// 大括号内部可以放入任意的 JavaScript 表达式,可以进行运算,以及引用对象属性。
{
let a = 1;
let b = 2;
console.log(`${a+b}`) //3
console.log(`${a*b}`) //2
}
//直接调用函数
{
function fn() {
return "Hello World";
}
console.log(`${fn()}`) //Hello World
}
</script>
<script>
// 模板字符串甚至还能嵌套。
const tmpl = addrs => `
<table>
${addrs.map(addr => `
<tr><td>${addr.first}</td></tr>
<tr><td>${addr.last}</td></tr>
`).join('')}
</table>
`;
const data = [{
first: '<Jane>',
last: 'Bond'
},
{
first: 'Lars',
last: '<Croft>'
},
];
console.log(tmpl(data));
</script>
<script>
// 如果需要引用模板字符串本身,在需要时执行,可以写成函数。
let func = (name) => `Hello ${name}!`;
func('Jack') // "Hello Jack!"
</script>
<script>
</script>
</html>