2009-12-24 54 views
0

我一直在這一段時間,我似乎無法破解它..我有一些JavaScript試圖隱藏兄弟divs,除了一個通過函數。這裏的HTML:javascript,無法檢索兄弟節點

<div id = "chat_content"> 
    <div id = "chat_content_1">This is div one</div> 
    <div id = "chat_content_2">This is div two</div> 
    <div id = "chat_content_3">This is div three</div> 
</div> 

而這裏的JavaScript的:

function showGroup(id) 
    { 
     // show the the div that was clicked 
     var e = document.getElementById(id); 
     e.style.display = 'block'; 

     // hide the others divs under the same parent 
     var children = e.parentNode.childNodes; 
     for (var i = 0; i < children.length; i++) 
     { 
      if (children[i] != e) 
      { 
       children[i].style.display = 'none'; 
      } 
     }; 
    } 

的感謝!和節日快樂:)

回答

0

考慮使用jQuery。讓生活更輕鬆。 檢查出來here

$("div#chat_content").siblings().css("display", "none"); 
+0

謝謝你。也應該是兄弟姐妹()! – Matt

0

有沒有你不使用previousSiblingnextSibling任何理由?您的代碼應在理論工作,但因爲它顯然不(你檢查你的錯誤控制檯?),請嘗試使用一種迭代的想法,而不是一個數組循環,其工作原理如下:

// hide the others divs under the same parent 
var child = e.parentnode.firstChild; 

do 
    { 
    if (child != e) 
     { 
     child.style.display = 'none'; 
     } 
    child = child.nextSibling; 
    } 
while (child.nextSibling != null); 

我第二順便提一下,使用jQuery之類的建議。它確實讓事情變得更簡單。

+0

嗯,它說child.style是未定義的。 我會給jquery一個鏡頭,但你有什麼想法,爲什麼這不起作用? 謝謝! – Matt

+0

我不確定問題出在哪裏。它應該像你的代碼一樣工作。也許沒有兄弟姐妹,或者你的目標是錯誤的。或者,也許你有非工作代碼,現在該頁面不會因爲緩存而被更新? – Dustin