徐州网站建设咨询,企业内部网站源码,wordpress前台用户中心,网站建设找谁做之所以写这篇文章#xff0c;是因为标签模板是一个很容易让人忽略的知识点
首先我们已经非常熟悉模板字符串的使用方法
const name 诸葛亮
const templateString hello, My name is ${name}标签模板介绍
这里的标签模板其实不是模板#xff0c;而是函数调用…之所以写这篇文章是因为标签模板是一个很容易让人忽略的知识点
首先我们已经非常熟悉模板字符串的使用方法
const name 诸葛亮
const templateString hello, My name is ${name}标签模板介绍
这里的标签模板其实不是模板而是函数调用的一种特殊形式
“标签”指的就是函数函数名紧跟在后面的模板字符串就是它的参数
比如下面的代码可以正常运行
alerthello world如果模板字符里面有变量就不是简单的调用了而是会将模板字符串先处理成多个参数再调用函数
const name 诸葛亮
const age 18console.loghello ${name}, I know your age is ${age}控制台打印如下
const name 诸葛亮
const age 18const tag (stringArr, ...args) {console.log(stringArr, stringArr)console.log(args, args)
}taghello ${name}, I know your age is ${age}
// 相当于调用函数tag, tag([hello , , I know your age is , ], 诸葛亮, 18)控制台打印如下
使用场景
过滤 HTML 字符串防止用户输入恶意内容
function saferHTML(templateData) {let s templateData[0];for (let i 1; i arguments.length; i) {let arg String(arguments[i]);s arg.replace(//g, amp;).replace(//g, lt;).replace(//g, gt;);s templateData[i];}return s;
}const string scriptalert(恶意代码)/script;
const content saferHTMLp${sender}富文本内容/p;
// plt;scriptgt;alert(恶意代码)lt;/scriptgt;富文本内容/p多语言转换
i18nWelcome to China!
// 欢迎来到中国将命令式编程转为声明式编程
// 命令式编程
const url xxxxxxx
a.style.color red
a.style.backgroundColor blue
a.style.fontSize 18px
a.style.lineHeight 26px
a.href https://${url}
a.target _blank
a.textContent 点击跳转// 声明式编程
a.stylescolor: red;backgroundColor: blue;fontSize: 18px;lineHeight: 26px;
.propshref: https://${url};target: _blank;
.content点击跳转