這看起來很簡單,但發現嘗試了很多東西真的很難。
基本上我想用 js 搜索 dom 并找到一個單詞的每個實體并將其替換為另一個。這很容易做到。
function replaceAllText(text) {
var walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT,
null,
false
);
while (walker.nextNode()) {
walker.currentNode.innerHTML = walker.currentNode.innerHTML.replaceAll(/hello/ig, text);
}
}
replaceAllText('Holla');
困難的是我只想在某些標簽上執行它,例如我不希望它替換 A 標簽內的文本。
現在我認為跳過 A 標簽會很容易,我可以這樣做。
function replaceAllText(text) {
var walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT,
null,
false
);
while (walker.nextNode()) {
if (walker.currentNode.tagName !== 'A') {
walker.currentNode.innerHTML = walker.currentNode.innerHTML.replaceAll(/hello/ig, text);
}
}
}
replaceAllText('Holla');
這仍然將文本放置在 A 標記內。
我在這里有一個示例,我正在使用
為此,請參閱它用 holla 替換所有 hello 實體,但 A 標記內除外。

uj5u.com熱心網友回復:
然后我們需要查看文本節點
請注意,stacksnippet 中的正文包括整個檔案,因此我也排除了腳本標簽
另請注意,我創建了一個正則運算式并測驗并替換不區分大小寫
最后我也忽略了鏈接內的標簽
const replaceAllText = (fromText, toText) => {
document.body.querySelectorAll("*")
.forEach(tag => {
if (tag.closest("A")) return; // A and nested tags inside A tags
if (["SCRIPT"].includes(tag.tagName)) return; // we can add more here
[...tag.childNodes].forEach(node => {
if (node.nodeType === Node.TEXT_NODE) {
const nodeText = node.textContent;
if (!nodeText.toUpperCase().includes(fromText.toUpperCase())) return;
console.log(nodeText);
node.textContent = nodeText.replace(new RegExp(fromText,"ig"), toText)
}
});
});
}
replaceAllText('Hello','Holla');
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<p>this is some test hello world</p>
<div class="Hello">Hello world! <a href="">Hello</a></div>
<div class="Hello">Hello world! <a href=""><span>Hello</span></a></div>
</body>
</html>
uj5u.com熱心網友回復:
您當前的方法看起來不錯。您只需要考慮innerHTML回傳的所有html內容,包括嵌套標簽。這就是為什么您的函式也替換了a標簽內的文本。
使其作業的一種方法是僅采用文本節點,并過濾掉a標簽內的文本節點,即其父節點的標簽名稱為A。
var rejectScriptTextFilter = {
acceptNode: function(node) {
if (node.parentNode.nodeName !== 'A') {
return NodeFilter.FILTER_ACCEPT;
}
}
};
function replaceAllText(text) {
var walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT,
rejectScriptTextFilter,
false
);
while (walker.nextNode()) {
var node = walker.currentNode;
node.nodeValue = node.nodeValue.replaceAll(/hello/ig, text);
}
}
replaceAllText('Holla');
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<p>this is some test hello world</p>
<div class="Hello">Hello world! <a href="">Hello</a></div>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/505650.html
標籤:javascript 正则表达式 搜索
上一篇:如何隨機播放串列串列?
