2012-04-26 410 views
1

我目前使用.replace函數替換頁面上的特定字符串。由於我不知道當前字符串所在,所以我不能選擇它,我的代碼看起來是這樣的:使用jQuery替換和正則表達式替換字符串

$('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> 
+0

的事情是,我試圖使它儘可能通用,所以它可以用於任何頁面。我用一個例子編輯了這篇文章。 – jsllsj 2012-04-26 23:20:15

+0

所以你正在尋找一個更簡潔的方式來做到這一點? – 2012-04-26 23:31:14

+0

我正在尋找一種方法來做到這一點,而無需更換整個dom。這似乎打破了很多頁面,其中有任何js。 – jsllsj 2012-04-26 23:37:49

回答

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標誌,你在通過正則表達式。

+0

這似乎是唯一的方法來做到這一點。謝謝! – jsllsj 2012-04-27 00:19:25

+0

@jsllsj - 我添加了一個特定的樹行走功能,應該做你想做的。 – jfriend00 2012-04-27 00:41:32

+0

@ jfriend代碼的工作版本[這裏](http://jsfiddle.net/kbj2j/4/)。替換「iPhone」的出現,但不會替換JavaScript函數中的文本。 – 2012-04-27 19:21:38