模板字符串
# 模板字符串
通常我们会在 js 里进行对某个标签进行追加元素,通常使用的是字符串拼接的方式来实现。这样一个引号里面包裹着另一个单引号,然后再用加号进行连接,这样是否会比较麻烦呢。
所以在
es6
里有一个模板字符串的功能,就是使用tab
键上的反引号进行包裹,变量使用${变量名}
的方式来使用。
# 旧式追加字符串
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>模板字符串</title>
</head>
<body>
<div class="box"></div>
<script>
const oBox = document.querySelector('.box')
let id = 1,
name = 'wujie'
oBox.innerHTML = '<ul><li><p id=' + id + '>' + name + '</p></li></ul>'
</script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 使用模板字符串
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>模板字符串</title>
</head>
<body>
<div class="box"></div>
<script>
const oBox = document.querySelector('.box')
let id = 1,
name = 'wujie'
let htmlStr = `<ul>
<li>
<p id="${id}">${name}</p>
</li>
</ul>`
// 追加 标签
oBox.innerHTML = htmlStr
</script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
编辑 (opens new window)
上次更新: 2021/10/23, 15:40:38