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



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

.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(( 函数吗?我不想使用任何外部库来仅使用此函数!

使用正则表达式将 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>

相关内容

  • 没有找到相关文章

最新更新