2010-03-26 9 views
3

텍스트 바꾸기를 시도하고 있지만 그렇게하려면 div의 텍스트 노드를 반복해야합니다.div 안에있는 텍스트 노드를 반복합니다.

각 Div는 클릭하면 아약스를 통해로드되며 적절한 콘텐츠입니다. 그런 다음 텍스트 내부에서 텍스트 노드를 교체해야합니다.

현재 코드는 아약스 내용을로드 한 후 전체 페이지의 모든 텍스트 노드를 반복하므로 너무 많은 리소스를 사용합니다.

나는 ...

을 사업부 통해 방법을 모두 루프를 발견하고, 텍스트 노드를 얻으려고 시간 동안 찾고있는이 파이어 폭스, 구글 크롬 및 6으로 작동한다.

의견이나 제안이 있으십니까?

function ajaxLoader(url, id) { 
    if (document.getElementById) { 
     var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(); 
    } 
    if (x) { 
     x.onreadystatechange = function() { 
      if (x.readyState == 4 && x.status == 200) { 
       el = document.getElementById(id); 
       el.innerHTML = x.responseText; 
      } 
     } 
     x.open("GET", url, true); 
     x.send(null); 
    } 
    // alert(id); 
    CheckTranslate(id); 
    // setTimeout('CheckTranslate(this);', 1000); 

} 

function CheckTranslate(id) { 

    // function to get text of a node 
    var content = function (node, txt) { 
     if (txt) { 
      if (node.textContent) { 
       node.textContent = txt; 
      } else if (node.nodeValue) { 
       node.nodeValue = txt; 
      } 
     } else { 
      return node.textContent ? node.textContent : node.nodeValue; 
     } 
    }; 
    // recuse div by id content 
    $("#"+id).each(function() { 
     // assign object handler 
     var obj = $(this).html(); 

     // check how many text nodes there 
     var mylen = obj.length; 

     if (mylen > 0) { 
      // loop thru each text node 
     } 
    }); 
    // recurse ajax content 
    (function (parent) { 
    var childs = parent.childNodes; 

    // if there are children to this 
    if (childs && childs.length) { 

     // loop through each text node 
     for (var i = 0, node; node = childs[i]; i++) { 

     // text node found, do the replacement   
     if (node.nodeType == 3) { 

      // grab value of current text node 
      var value = content(node); 

      // grab class name of current text node 
      var myclass = $(this).attr("class"); 

      // grab data property of this node 
      var ist = $(this).data('translated'); 

      // check if this is correct class and has no data property and value is not undefined 
      if (typeof(value) != 'undefined' && myclass != 'box_title' && ist != 'yes' && (myclass == 'status_bar' || myclass == '' || myclass == 'box_title_small' || myclass == 'status_bar_select')) { 

       // loop thru english array to find matches 
       for (var x = 0; x < en_count; x++) { 

        // get current english phrase 
        var from = en_lang[x]; 

        // get current other language phrase 
        var to = other_lang[x]; 

        if (value.match(from)) { 

         content(node, value.replace(from, to)); 
         if ($.browser.msie == 'false') { 
          $(node).data('translated', 'yes'); 
         } 
        } 
        // end check value match 
       } 
      } 
     } else { 
      arguments.callee(node); 
     } 
    } 
    } 
    })(document.body); 
} 

2 개 기능, div에 대한 아약스 내용을로드 ajaxLoader, 다음 새 내용이로드 된 후 변환을 수행하는 CheckTranslate있다 :

는 요청으로, 여기에 코드입니다.

문제는 기능 (부모) 섹션이 모든 텍스트 노드를 살펴 보는 것입니다. 성능을 위해 div 내 텍스트 노드 만 볼 수 있습니다.

하지만 난 그냥 ... 그 참조하는 방법을하지 않는

물건을 밖으로의이 종류를 파악하는 것은 매우 어렵습니다, 그리고 jQuery의 설명서를 배울 정말 쉽지 않다 ...

+0

포스트 코드, 그것은 것 "텍스트 노드"로 무엇을 의미하는지 힌트를주십시오. –

답변

-1

이런 종류의 것을 찾고 계십니까?

$(".your_ajax_div_class").each(function(i){}); 

당신은 아마 추가 할 수 없거나 내용이로드 된 후에 둥지이 나 ajaxComplete() 함수 내에서 비슷한 일을 트리거 할 수 있습니다.

+0

하지만 내 div에서 텍스트 노드를 식별하고 가져 오는 방법은 무엇입니까? 아니, 클래스 이름을 사용할 수 없지만 내 코드에서 div의 ID가 전달됩니다. 그래서 나는 그것에 접근 할 수 있습니다. – crosenblum

+0

찾기/바꾸기까지 수행하려는 작업의 예를 보는 것이 도움이됩니다. DIV의 특정 노드 노드에 접근하려고합니까? 그렇지 않다면 내가 게시 한 함수 안에 $ (this) .html()에 액세스하여 DIV의 내부 HTML에 액세스하십시오. – Todd

5

내가 거기에이 할 수있는 더 나은 방법이, 그러나 일반 자바 스크립트에서, 당신은 단지 재귀 함수 쓸 수 있습니다 확신 :

function ReplaceChildText(node, findText, replaceText) { 
    if (node.nodeType == 3) { 
     node.innerHTML = node.innerHTML.replace(findText, replaceText); 
    } else { 
     for (var child in node.childNodes) { 
      ReplaceChildText(child, findText, replaceText); 
     } 
    } 
} 

당신은 다음과 같이 호출 할 수 있습니다

ReplaceChildText(document.getElementById('divID'),'findText','replacement'); 
+0

내 문제는 div 내에서만 그렇게하는 것입니다. 전체 페이지가 아닌. 나는 그 부분 만하는 완전히 분리 된 코드를 가지고있다. – crosenblum

+0

함수를 호출 할 때 div를 전달하면 div와 해당 자식 만 처리합니다 ... – tloflin

+0

div 안에있는 각 텍스트 노드를 반복 할 수 있습니까? – crosenblum

-1

을 텍스트 노드 란 말을 의미합니까?

당신은 배열로 단어를 구분 split를 사용할 수 있습니다

var str = $("div").text().split(' '); 
이 같은 DIV

:

<div>red blue green orange</div> 

겠습니까 출력 :

["red", "blue", "green", "orange"] 
+0

그는 DOM 컨텍스트의 텍스트 노드를 의미합니다. – LeeGee

관련 문제