我想找到并替换多个单词?我发现这个代码这是工作正常,但只有一个文本工作,我怎么能添加多个单词。
var observer = new MutationObserver(onMutation);
observer.observe(document, {
childList: true, // report added/removed nodes
subtree: true, // observe any descendant elements
});
function onMutation(mutations, observer) {
for (var i = 0, len = mutations.length; i < len; i++) {
var added = mutations[i].addedNodes;
for (var j = 0, node; (node = added[j]); j++) {
replaceText(node);
}
}
}
function replaceText(el) {
let target_string = "winter";
let replacement_string = "summer";
const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
for (let node; (node = walker.nextNode());) {
const text = node.nodeValue;
const newText = text.replace(target_string, replacement_string);
if (text !== newText) {
node.nodeValue = newText;
}
}
}
1条答案
按热度按时间b09cbbtk1#
您可以尝试使用dict执行相同的代码,其中dict的键、值表示目标和替换字符串。