【问题标题】:How to show all child nodes in jQuery如何在jQuery中显示所有子节点
【发布时间】:2012-11-25 06:36:08
【问题描述】:
<a href="javascript:(void);" id="lnkP">show all children</a>
<a href="javascript:(void);" id="lnkC1">hide child 1</a>
<a href="javascript:(void);" id="lnkC2">hide child 2</a>

<div id="p" style="display:none;">
<div id="c1">child 1</div>
<div id="c2">child 1</div>...
</div>​

$("#lnkP").click(function(){
    $("#p").children().show(); //seems there's a problem here...
});
$("#lnkC1").click(function(){
   $("#c1").hide(); 
});
$("#lnkC2").click(function(){
   $("#c2").hide(); 
});​

jsFiddle:http://jsfiddle.net/CBGsF/1/

我想做的是:

  1. p 是父容器
  2. 点击show all children链接,显示 p 下的所有子 div
  3. 点击lnkC1lnkC2隐藏 单个子div

但我似乎没有让.children() 正常工作。那么如何解决呢?有什么想法吗?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

(代表问题作者发布解决方案)

我认为.children() 也会搜索不可见的节点。好吧,我错了。

【讨论】:

    【解决方案2】:

    由于父级(在您的情况下为#p)有一个display:none,它的子级将不可见。

    您需要先显示父母,

    $("#p")
    .show()
    .children().show();
    

    (jQuery的链接,很有帮助)

    请尝试摆脱内联样式(一段时间后变得无法管理),尽可能使用类。

    你可以在 css 中有一个类,

    .displayNone
    {
        display: none;
    } 
    .displayBlock
    {
       display: block;
    }
    

    然后使用 jquery 方法 .removeClass().addClass().toggleClass() 来显示/隐藏您的元素。

    这只是一个建议:)

    测试链接:http://jsfiddle.net/CBGsF/8/

    【讨论】:

      【解决方案3】:

      您还需要显示#p

      更新小提琴:http://jsfiddle.net/CBGsF/7/

      $("#lnkP").click(function(){
          $("#p").show().children().show(); //Add show() before children.show call
      });
      $("#lnkC1").click(function(){
         $("#c1").hide(); 
      });
      $("#lnkC2").click(function(){
         $("#c2").hide(); 
      });​
      

      【讨论】:

        【解决方案4】:

        父元素设置为"display":"None" 就是这个问题

        $("#p").css("display","block"); //is required in show all anchor click
        

        检查小提琴

        http://jsfiddle.net/CBGsF/6/

        谢谢

        【讨论】:

          【解决方案5】:

          更新小提琴:http://jsfiddle.net/CBGsF/5/

          $("#lnkP").click(function(){
          $("#p").show();
          $("#p").children().show();
          });
            $("#lnkC1").click(function(){
             $("#c1").hide(); 
          });
          $("#lnkC2").click(function(){
             $("#c2").hide(); 
          });​
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-07-29
            相关资源
            最近更新 更多