我正在制作一个书签,将所有字母(例如“ R”)更改为其他字母(例如“ W”),或者可能替换整个单词。我尝试使用下面的代码,但它使网站混乱,并在元素中显示了元素。
javascript: $("body").text($("body").text().replace("r", "w"));
是否有解决方案?
对于那些想知道我将如何使用它的人,我正在尝试编写一个可以解决这个问题的代码:
你好,我叫乔纳森·格拉斯韦尔,我想提出一个关于拖拉机的新主意。
进入此:
哎呀,我的女ame是乔纳西恩·格怀斯韦夫,我想用威耐特的名字来歪歪歪歪的偏见。
[基本上是“ OWOfier”。另外,是否可以在一段时间后20%的时间插入随机图释?]
BODY,如果包含HTML内容。您的问题就在$("body").text($
,因为在.text(
中您说的是:“使正文成为此文本:”失去了整个标记。您应该改为遍历3
(Node.TEXT_NODE
)的每个NodeType,或者使用TreeWalker API
const body = document.body; // Or whatever more specific element you desire
const repl = { // Your replacements:
"l" : "w",
"L" : "W",
"r" : "w",
"R" : "W",
"\\." : ". :)" // Remember, escape RegExp special characters to treat them as literals
};
const treeWalker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT);
while (treeWalker.nextNode()) {
const Node = treeWalker.currentNode; // PS: Node.nodeType is always 3
Object.keys(repl).forEach(key => {
Node.nodeValue = Node.nodeValue.replace(new RegExp(key, "g"), repl[key]);
});
}
.hello, .ll {color: BURLYWOOD;} /* "l"s of "class" and "hello" will stay intact */
<h1 class="hello">Hello,</h1>
<p>
my name is <b class="ll">Jonathan Grasswell</b>,
and I would like to propose a new idea. For a tractor. LOL
</p>
方法text()
仅返回正文的文本内容。
尝试此功能,请按F12键在此页面的控制台下运行此功能,同时将“ Jonathan”替换为“ ABCDEFGHIJKLMN”。
function replaceTextOfElement(element) {
$(element).contents()
.filter((_, child) => child.tagName !== 'SCRIPT' && child.tagName !== 'STYLE' && child.tagName !== 'IFRAME')
.each((_, child) => {
if(child.nodeType === Node.TEXT_NODE) {
child.data = child.data.replace('Jonathan', 'ABCDEFGHIJKLMN');
} else {
replaceTextOfElement(child);
}
});
}
replaceTextOfElement($('body'));