【问题标题】:javascript, can't retrieve sibling nodesjavascript,无法检索兄弟节点
【发布时间】:2009-12-24 23:47:06
【问题描述】:

我已经有一段时间了,但我似乎无法破解它。我有一些 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';
            }
        };
    }

谢谢!节日快乐:)

【问题讨论】:

    标签: javascript html hide show


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您有什么理由不使用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 之类的东西。它确实使事情变得更容易。

      【讨论】:

      • 嗯,它说 child.style 是未定义的。我会给 jquery 一个机会,但你知道为什么这不起作用吗?谢谢!
      • 我不确定是什么问题。它应该可以工作,就像您的代码一样。也许没有兄弟姐妹,或者您的目标是错误的元素。或者您的代码无法正常工作,而现在页面由于缓存而没有更新?
      猜你喜欢
      • 2012-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多