我目前正在使用.replace函数替换页面上的特定字符串。鉴于我不知道当前字符串的位置,所以我无法选择它,我的代码看起来像这样:
$('body').html( $('body').html().replace(regex, 'sometext') );
因此,如果页面最初看起来像这样:
<div class="a">Hello</div>
It now looks like this:
<div class="a">sometext</div>
有没有办法不使用$('body').html( $('body').html().replace() )
?
谢谢!
编辑:示例
<p class="last">Mac, iPhone, iPod and iPad customers within 90 days of ownership are eligible for complimentary phone support — one support incident per iPod and unlimited incidents per Mac, iPhone and iPad. <a href="/support/" onclick="s_objectID="http://www.apple.com/support/_3";return this.s_oc?this.s_oc(e):true">Online technical support</a> for Apple products is available beyond the initial 90 days.</p>
使用此:
$('body').html( $('body').html().replace("iPhone", '<a href="#">iPhone</a>') );
它将取代iPhone的每个实例,使其看起来像iPhone
导致:
<p class="last">Mac, <a href="#">iPhone</a>, iPod and iPad customers within 90 days of ownership are eligible for complimentary phone support — one support incident per iPod and unlimited incidents per Mac, <a href="#">iPhone</a> and iPad. <a href="/support/" onclick="s_objectID="http://www.apple.com/support/_3";return this.s_oc?this.s_oc(e):true">Online technical support</a> for Apple products is available beyond the initial 90 days.</p>
答案 0 :(得分:3)
您可以逐个节点地遍历DOM层次结构,检查文本节点,然后比较每个单独文本节点中的文本。这将消除您当前代码可能导致的破损类型。它可以避免像当前代码那样破坏所有事件处理程序。
仅供参考,这里是我为a different answer写的一个不同功能的修改,可以做你想做的事情:
function replaceTextInDomTree(root, searchRegEx, replace) {
var node = root.firstChild;
while(node) {
if (node.nodeType == 3) {
if (searchRegEx.test(node.nodeValue)) {
// we do the test first to avoid setting
// nodeValue when there's no change
// to perhaps save the browser some layout time
// since we'd be operating on every single text node
node.nodeValue = node.nodeValue.replace(searchRegEx, replace);
}
}
if (node.hasChildNodes()) {
// go down into the children
node = node.firstChild;
} else {
while (!node.nextSibling) {
node = node.parentNode;
if (node == root) {
return;
}
}
node = node.nextSibling;
}
}
}
注意:
1)这将替换连续文本块中的文本,但不包含HTML标记。
2)如果你想在同一个文本节点中进行多次替换,那么一定要把g标志放在你传入的正则表达式中。