javascript,无法检索兄弟节点

时间:2009-12-24 23:47:07

标签: javascript html hide show

我已经有一段时间了,我似乎无法解决它..我有一些javascript试图隐藏兄弟div,除了通过该函数传递的那个。这是html:

<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';
            }
        };
    }

谢谢!和节日快乐:)

2 个答案:

答案 0 :(得分:0)

考虑使用jQuery。让生活更轻松。 查看here

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

答案 1 :(得分: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的东西。它确实使事情变得更容易。

相关问题