JavaScript 中的模板字符串。
ES6 引入了模板以便在字符串中嵌入表达式。它使用反引号 (``) 而不是 '' 或 "" 引号。它提供了一种更好的字符串内插方法,并且可以使用类似 ${a+b} 的方式嵌入表达式。它提供的语法比 + 操作符好很多。
下面是 JavaScript 中模板字符串的代码 −
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 20px;
font-weight: 500;
color: blueviolet;
}
</style>
</head>
<body>
<h1>Template strings in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to add two numbers and display them</h3>
<script>
let resEle = document.querySelector(".result");
let a = 22;
let b = 44;
function add(a, b) {
return a + b;
}
document.querySelector(".Btn").addEventListener("click", () => {
resEle.innerHTML = `The sum of ${a} and ${b} = ${add(a, b)}`;
});
</script>
</body>
</html>输出

点击“单击此处”按钮后 −

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP