JavaScript 中的标记模板文字
javascriptweb developmentobject oriented programming更新于 2025/9/4 15:40:17
模板文字还允许我们创建标记模板文字。标记文字就像一个函数定义,允许我们解析模板文字。标记文字不包含括号,标记函数将字符串值数组作为第一个参数。其余参数随后传递给其他相关参数。
以下是在 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>Tagged Template Literals in JavaScript</h1>
<div class="result"></div>
<br />
<button class="btn">点击此处</button>
<h3>Click on the above button to pass the template string using tagged template literal to sampleTag() function</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelector(".Btn");
function sampleTag(strings, name, age, rollNo) {
let section;
if (rollNo > 50) {
section = "A";
} else {
section = "B";
}
return `${name} roll no: ${rollNo} age :${age} is in section ${section}`;
}
let name = "Rohan",
age = 16,
rollNo = 22;
BtnEle.addEventListener("click", () => {
resEle.innerHTML = sampleTag`${name} aged ${age} and roll no ${rollNo} is new in
the school`;
});
</script>
</body>
</html>
输出

点击‘点击此处’按钮 −

相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

