2012-06-06 75 views
1

我們已經有很長的聊天here與DOM操縱rlemon。基本上問題是'How can I change the UL-LI DOM with Javascript?'例如,假設我想要顯示類似"<ul><li><i>Hello 1, have a nice day!</i></li>...</ul>"的東西 - 而不是"<ul id='uids'><li>1</li><li>2</li></ul>" - 我怎麼能只用DOM操作來做到這一點?如何在使用Javascript的UL-LI塊中簡單進行DOM操作?

我知道這是一個簡單的問題,所以不是重新發明輪子,我很滿意引用。

有關DOM操作的簡單演示,你能做這樣的事嗎?

輸入

<ul id="uid"> 
      <li>1</li> 
      <li>2</li> 
    </ul> 

輸出

<ul id="uid"> 
      <li>Hello beautful lady 1!</li> 
      <li>Hej gentleman 2.</li> 
    </ul> 

也許有用其他新手來熟悉JS

的功能性質
  1. http://chat.stackoverflow.com/rooms/17/conversation/learn-javascript-videos

  2. http://ejohn.org/apps/learn/

+0

你能告訴你開始用加價,和你想結束了加價?我不完全清楚你想要什麼(我讀了聊天,但是......可能我有點緊張,對不起!)。 –

+0

你想改變李元素的文字內容嗎?不是那麼簡單..? – dmp

+0

好的,這是一個學習者的問題。我會盡力給你一個很好的例子。 – dmp

回答

4

短的方式,使用的innerHTML:

var lis = document.getElementById("uid").getElementsByTagName("li"); 
for(var i = 0; i < lis.length; i++) 
    lis[i].innerHTML = "<i>Hello "+lis[i].innerHTML+", have a nice day!</i>"; 

jsFidlde:http://jsfiddle.net/eZv4D/3/

很長的路,與真正的DOM操作:

var lis = document.getElementById("uid").getElementsByTagName("li"); 
for(var i = 0; i < lis.length; i++) { // Loop through all <li> elements 
    // Create an <i> element to contain the text 
    var el = document.createElement("i"); 

    // Add the start of the text to the <i> 
    el.appendChild(document.createTextNode("Hello ")); 
    // Add everything in the <li> to the <i> (they are removed from the <li>) 
    while(lis[i].firstChild) 
     el.appendChild(lis[i].firstChild); 
    // Add the end of the text to the <li> 
    el.appendChild(document.createTextNode(", have a nice day!")); 

    // Add the <i> to the <li> 
    lis[i].appendChild(el); 
} 

的jsfiddle:http://jsfiddle.net/eZv4D/2/

2

一種方法如下:

var liElems = document.getElementsByTagName('li'), 
    strings = ['Hello beautiful lady ','Hej gentlemen ']; 

for (var i = 0, len = liElems.length; i < len; i++){ 
    elem = liElems[i].firstChild, 
    curText = elem.nodeValue; 
    if (i%2 == 0){ 
     elem.nodeValue = strings[0] + curText; 
    } 
    else { 
     elem.nodeValue = strings[1] + curText; 
    } 
} 

JS Fiddle demo

參考文獻:

1

這裏的另一種方法:

http://jsfiddle.net/cWRPZ/

開始:

<ul> 
    <li>1</li> 
    <li>2</li> 
</ul> 

和JS是..

var demo = { 
    __elems: false, 
    replacement: 'This is element __replaceme__', 
    go: function(){ 
     this.__elems = document.querySelectorAll('li'); 
     for(var i = 0; i < this.__elems.length; i++){ 
      elem = this.__elems[i]; 
      elem.firstChild.nodeValue = this.replacement.replace('__replaceme__',elem.firstChild.nodeValue); 
     }     
    } 
} 

demo.go(); 

要記住一些重要的事情,也有a few nodeTypes在DOM中,並不是所有的都會是你以後的,所以你應該過濾。如果有一個評論節點,例如,在文本前面,那麼這將不會像你期望的那樣工作。

+1

可能應該使用'querySelectorAll('#uids li')',否則它與'getElementsByTagName'沒有什麼不同。很高興被提醒該函數存在,儘管它不起作用IE7。 – Brilliand

+0

'document.getElementById(「uid」)。getElementsByTagName(「li」)'儘管可讀性較差,並不像所有時髦選擇器一樣快得多(QSA非常快但比較慢),並且不會限制你到一個靜態節點列表,只是我的2美分)如果你要去選擇器路由只使用Sizzle,然後至少你有一些交叉兼容性 – rlemon

1

「Unlearning is very hard」。

我分析與視頻中的大約44.00點here引入的工具JSLint的here他們的代碼。 Brilliand的簡單版本的規格(?)錯誤數量最小。視頻提到稱爲ES3.1的東西即將到來,無論如何,我沒有資格說它們現在是否是正確的 - 取決於規格(根據視頻,從1999年開始是目前的規格)。無論如何,我傾向於使用簡單的方法,關於分析的反饋?

大衛·托馬斯

'document' was used before it was defined. 
var liElems = document.getElementsByTagName('li'), 
line 2 character 40Missing space between ',' and 'Hej gentlemen '. 
    strings = ['Hello beautiful lady ','Hej gentlemen ']; 
line 4 character 6Move 'var' declarations to the top of the function. 
for (var i = 0, len = liElems.length; i < len; i++){ 
line 4 character 6Stopping. (30% scanned). 

Brilliand

簡單

'document' was used before it was defined. 
var lis = document.getElementById("uid").getElementsByTagName("li"); 
line 2 character 4Missing space between 'for' and '('. 
for(var i = 0; i < lis.length; i++) 
line 2 character 5Move 'var' declarations to the top of the function. 
for(var i = 0; i < lis.length; i++) 
line 2 character 5Stopping. (66% scanned). 

DOM -version

'document' was used before it was defined. 
var lis = document.getElementById("uid").getElementsByTagName("li"); 
line 2 character 4Missing space between 'for' and '('. 
for(var i = 0; i < lis.length; i++) { // Loop through all <li> elements 
line 2 character 5Move 'var' declarations to the top of the function. 
for(var i = 0; i < lis.length; i++) { // Loop through all <li> elements 
line 2 character 5Stopping. (12% scanned). 

danp

Unexpected dangling '_' in '__elems'. 
    __elems: false, 
line 4 character 17Expected exactly one space between 'function' and '('. 
    go: function(){ 
line 4 character 19Expected exactly one space between ')' and '{'. 
    go: function(){ 
line 4 character 19Missing space between ')' and '{'. 
    go: function(){ 
line 5 character 9Missing 'use strict' statement. 
     this.__elems = document.querySelectorAll('li'); 
line 5 character 14Unexpected dangling '_' in '__elems'. 
     this.__elems = document.querySelectorAll('li'); 
line 5 character 24'document' was used before it was defined. 
     this.__elems = document.querySelectorAll('li'); 
line 6 character 12Missing space between 'for' and '('. 
     for(var i = 0; i < this.__elems.length; i++){ 
line 6 character 13Move 'var' declarations to the top of the function. 
     for(var i = 0; i < this.__elems.length; i++){ 
line 6 character 13Stopping. (46% scanned). 
undefined 
document 'go' 4 

rlemon

'document' was used before it was defined. 
var list = document.getElementById('uids'), // get the parent ul 
line 3 character 45Expected exactly one space between 'function' and '('. 
Array.prototype.forEach.call(items, function(item) { // because nodeLists are not arrays we do this for a forEach 
line 4 character 5Missing 'use strict' statement. 
    var value = item.textContent || item.innerText; // gets the text content cross browser 
line 5 character 10Expected exactly one space between 'while' and '('. 
    while(item.hasChildNodes()){ // this just removes the contents of the li without innerHTML, and is faster for this amount of data 
line 5 character 32Expected exactly one space between ')' and '{'. 
    while(item.hasChildNodes()){ // this just removes the contents of the li without innerHTML, and is faster for this amount of data 
line 5 character 32Missing space between ')' and '{'. 
    while(item.hasChildNodes()){ // this just removes the contents of the li without innerHTML, and is faster for this amount of data 
undefined 
document 'items' 3 
clear 
1
var list = document.getElementById('uids'), // get the parent ul 
    items = list.getElementsByTagName('li'); // get the items as a nodeList 
Array.prototype.forEach.call(items, function(item) { // because nodeLists are not arrays we do this for a forEach 
    var value = item.textContent || item.innerText; // gets the text content cross browser 
    while(item.hasChildNodes()){ // this just removes the contents of the li without innerHTML, and is faster for this amount of data 
     item.removeChild(item.lastChild); 
    } 
    item.appendChild(document.createTextNode("Wuddup " + value)); // append your new message :P 
}); 

這是我的一個它,但是如果可能的話,在將這個列表輸出到文檔之前,如果可能的話,在服務器上執行此操作......這樣做更有意義。

Here is a DEMO對消息產生一點點旋轉;)

+0

我收集父e lement作爲一個變量,因爲,坦率地說,它並沒有爲處理做出不同的處理,並且它比.getById()。getByTagName()更具可讀性。 – rlemon

相關問題