2012-04-26 3 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> 

이 사용 :

<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> 
: 그것은 결과적으로 아이폰

같은

을 살펴 보겠습니다 있도록 아이폰의 각 인스턴스를 대체 할

$('body').html($('body').html().replace("iPhone", '<a href="#">iPhone</a>')); 

+0

것은 내가 일반적으로 그것을 만들려고한다을 가능한 한 너무 모든 페이지에서 작동 할 수 있습니다. 게시물을 예를 들어 편집했습니다. – jsllsj

+0

이렇게하면보다 간결한 방법을 찾고 있습니까? –

+0

전체 dom을 교체하지 않고이를 수행 할 방법을 찾고 있습니다. 이것은 그 안에 js가있는 많은 페이지를 망가 뜨리는 것 같습니다. – jsllsj

답변

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)

참고로, 여기 당신이 원하는 것을 할 것입니다 내가 a different answer에 대해 쓴 다른 기능의 수정입니다 그 안에 HTML 태그가 없습니다.

2) 같은 텍스트 노드에 여러 대체합니다 원하는 경우, g 플래그 당신이 전달 정규식을 넣어해야합니다.

+0

이것은 다른 방법으로 생각됩니다. 감사! – jsllsj

+0

@jsllsj - 원하는 트리 트렁크 함수를 추가했습니다. – jfriend00

+0

@ jfriend의 코드가있는 작업 버전 [here] (http://jsfiddle.net/kbj2j/4/). "iPhone"을 대치하지만 자바 스크립트 함수 내부의 텍스트는 대체하지 않습니다. –