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