如何在不使用任何库的情况下在一组所有匹配元素中显示双大括号之间的数据?

我想做一个可以做这样的事情的函数:


HTML :


 <h1 class="demo">I am {{ name }}</h1>

 <span class="demo">{{ name }} learn JavaScript</span>

JS:


data(".demo", {

   name: "Arc"

};

输出 :


 I am Arc

 Arc learn JavaScript

可以制作可以做到这一点的 data() 函数吗?我不想为了使用这个函数而使用任何外部库!


慕雪6442864
浏览 148回答 1
1回答

牧羊人nacy

使用正则表达式{{ .. }}将 HTML 中的 s替换为传递对象中的适当值(如果有):const data = (selector, obj) => {&nbsp; document.querySelectorAll(selector).forEach((elm) => {&nbsp; &nbsp; elm.textContent = elm.textContent.replace(&nbsp; &nbsp; &nbsp; /{{ *(\w+) *}}/g,&nbsp; &nbsp; &nbsp; // If key is in the obj, replace with the value&nbsp; &nbsp; &nbsp; // otherwise, replace with the match (make no changes):&nbsp; &nbsp; &nbsp; (match, key) => key in obj ? obj[key] : match&nbsp; &nbsp; );&nbsp; });};data(".demo", {&nbsp; &nbsp;name: "Arc"});&nbsp;<h1 class="demo">I am {{ name }}</h1>&nbsp;<span class="demo">{{ name }} learn JavaScript</span>如果您还需要考虑嵌套元素,则选择父级的所有文本节点,并执行相同的操作:const getTextNodes = (parent) => {&nbsp; &nbsp; // https://stackoverflow.com/questions/2579666/getelementsbytagname-equivalent-for-textnodes&nbsp; &nbsp; var walker = document.createTreeWalker(&nbsp; &nbsp; &nbsp; &nbsp; parent,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; NodeFilter.SHOW_TEXT,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; null,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; false&nbsp; &nbsp; );&nbsp; &nbsp; var node;&nbsp; &nbsp; var textNodes = [];&nbsp; &nbsp; while(node = walker.nextNode()) {&nbsp; &nbsp; &nbsp; &nbsp; textNodes.push(node);&nbsp; &nbsp; }&nbsp; &nbsp; return textNodes;}const data = (selector, obj) => {&nbsp; document.querySelectorAll(selector).forEach((elm) => {&nbsp; &nbsp; getTextNodes(elm).forEach((node) => {&nbsp; &nbsp; &nbsp; node.textContent = node.textContent.replace(&nbsp; &nbsp; &nbsp; &nbsp; /{{ *(\w+) *}}/g,&nbsp; &nbsp; &nbsp; &nbsp; // If key is in the obj, replace with the value&nbsp; &nbsp; &nbsp; &nbsp; // otherwise, replace with the match (make no changes):&nbsp; &nbsp; &nbsp; &nbsp; (match, key) => key in obj ? obj[key] : match&nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; });&nbsp; });};data(".demo", {&nbsp; &nbsp;name: "Arc"});span > span {&nbsp; background-color: yellow;}<h1 class="demo">I am {{ name }}</h1>&nbsp;<span class="demo">{{ name }} learn JavaScript <span> nested {{ name }} </span></span>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript