2010-03-29 115 views
0

我使用下面的代碼來替換div中的文本。但我需要循環通過特定的div,而不是頁面上的所有內容,即div的文本節點...通過傳遞div id,我可以更改文本替換的目標嗎?

我只是不明白如何引用下面的代碼中的div。

(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++) { 

更多的代碼的請求:

function npup(parent) { 
var children = parent.childNodes, child; 
for (var idx=0, len=children.length; idx<len; ++idx) { 
    child = children.item(idx); 
    alert(child); 
    if (child.nodeType===3) { 
    // it is a text node. do magic. 
    for (var x = 0; x < en_count; x++) { 
     // what is the current content of the current node 
     var value = content(child); 

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

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

     if (typeof(from) != 'undefined' && value.match(from)) { 
      content(node, value.replace(from, to)); 
     } 
    } 
} 
} 

} 變種theDiv =的document.getElementById( 'mydiv');

npup(theDiv);

+0

我想更改上面的代碼,只能循環通過div的文本節點。它已經循環遍歷頁面的所有文本節點。 – crosenblum 2010-03-29 20:37:22

+0

我想知道你的意思是文本節點。你是指3類型的DOM節點,還是其實是指其中包含文本的某些元素?請解釋你正在嘗試做什麼,你肯定會得到幫助。 在您最新的評論後,我改變了我的答案(下面),但我仍然不確定我是否完全瞭解你的內容。 – npup 2010-03-29 20:44:12

回答

1

編輯哦,我明顯誤解了你的問題。這裏是如何循環通過某些元素的文本節點:

function npup(parent) { 
    var children = parent.childNodes, child; 
    for (var idx=0, len=children.length; idx<len; ++idx) { 
     child = children.item(idx); 
     if (child.nodeType===3) { 
     // it is a text node. do magic. 
     } 
    } 
} 

我寫了這個純JavaScript的,因爲你的代碼示例是純js。爲了方便,像Prototype和jQuery這樣的庫的選擇器引擎通常會忽略檢索時的文本節點,因此不需要打擾它們。或者根據你對它的看法,去找他們。

+0

我們是否必須遍歷所有文本節點才能找到div中的那些節點?我們可以只指定div中的節點,其中我們已經有一個通過ID? – crosenblum 2010-03-29 20:38:31

+0

然後,父母是用來保存我們正在循環的div的ID的變量? – crosenblum 2010-03-29 20:44:53

+0

如果您將div傳遞給我上面給出的函數,該函數可讓您在div中的所有文本節點上進行神奇的操作。 通過首先在變量var theDiv = document.getElementById('theDivId');'中檢索它,然後將其提供給函數來傳遞函數div元素。 – npup 2010-03-29 20:47:45

相關問題