嘗試查找特定標簽中的所有單詞,例如所有 p 標簽,以便我可以對其應用一些正則運算式并替換所有單詞。
例如,
<p>the lazy cat went <div>up</div> to the cheery fox</p>
您可以選擇“所有單詞”正則運算式:
/\w /g
您可以使用 jquery 替換。這是我的代碼還沒有完全作業。
$("p").html($("p").html().replace(/\w /g, 'fox'));
現在我需要做的是讓它作業,以便將 p 標簽內的所有單詞替換為另一個單詞。結果:
<p>fox fox fox fox <div>fox</div> fox fox fox fox</p>
如何讓 jquery 替換p標簽內的所有單個單詞,但不影響其中的任何其他 HTML 或代碼?
uj5u.com熱心網友回復:
取而代之的是檢索所有文本節點,并對其進行迭代以將其內容重新分配給替換的字串。
const getAllTextNodes = (parent) => {
const walker = document.createTreeWalker(
parent,
NodeFilter.SHOW_TEXT,
null,
false
);
let node;
const textNodes = [];
while(node = walker.nextNode()) {
textNodes.push(node);
}
return textNodes;
};
for (const p of $('p')) {
for (const textNode of getAllTextNodes(p)) {
textNode.textContent = textNode.textContent.replace(/\w /g, 'fox');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>the lazy cat went up to the cheery fox</p>
或者拋棄 jQuery,因為它并沒有真正提供任何好處
const getAllTextNodes = (parent) => {
const walker = document.createTreeWalker(
parent,
NodeFilter.SHOW_TEXT,
null,
false
);
let node;
const textNodes = [];
while(node = walker.nextNode()) {
textNodes.push(node);
}
return textNodes;
};
for (const p of document.querySelectorAll('p')) {
for (const textNode of getAllTextNodes(p)) {
textNode.textContent = textNode.textContent.replace(/\w /g, 'fox');
}
}
<p>the lazy cat went up to the cheery fox</p>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/463707.html
