1

現在、ページ上の特定の文字列を置き換えるために .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=&quot;http://www.apple.com/support/_3&quot;;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=&quot;http://www.apple.com/support/_3&quot;;return this.s_oc?this.s_oc(e):true">Online technical support</a> for Apple products is available beyond the initial 90 days.</p>
4

1 に答える 1

3

DOM階層をノードごとに歩き、テキストノードをチェックしてから、個々のテキストノードのテキストを比較できます。これにより、現在のコードが引き起こす可能性のある種類の破損が排除されます。現在のコードのようにすべてのイベントハンドラーを壊さないようにします。

参考までに、これはあなたが望むことをする別の答えのために私が書いた別の関数の修正です:

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フラグを設定してください。

于 2012-04-26T23:39:11.857 に答える