开发者

jQuery having trouble showing hidden elements

I have some nested lists and was hoping to be able to have a "show all" button at the top, but it doesn't seem to work.

Any suggestions? I know there are probably other ways of accomplishing similar things, but I was using this as an opportunity to learn more about jquery and was trying to figure out why this particular example wasn't working.

Here is is in action: http://hortitude.com/samples/jquery_show_trouble.html

And the code....

<html>
<head>
    <script type="text/javascript" src="../jquery/jquery-1.4.4.js"></script>

    <script type="text/javascript">
      $( function () {
          $("h1").click ( function () {
              var subitems = $(".bar");
              $(".bar").show();
          });
          $(".foo").click ( function () {
              var obj = $(this);
              var children = obj.children();
              $(th开发者_开发知识库is).children().toggle (500);
          });

      });
    </script>


</head>
<body>
  <h1>show all</h1>
  <ul>
    <li class="foo">item 1
       <ul> 
         <li class="bar">sub-item 1</li>
         <li class="bar">sub-item 2</li>
       </ul>
    </li>
    <li class="foo">item 2
       <ul> 
         <li class="bar">sub-item 1</li>
         <li class="bar">sub-item 2</li>
       </ul>
    </li>
    <li class="foo">item 3
       <ul> 
         <li class="bar">sub-item 1</li>
         <li class="bar">ysub-item 2</li>
       </ul>
    </li>
  </ul>
</body>
</html>


You are hiding the <ul> elements, $(this).children() selects the <ul> elements inside the particular .foo element.
If any ancestor of a visible element is hidden, then the element will still be hidden, thus $('.foo').show() has no effect.

Do

$(".foo").children().show();

Btw. a heading element (<h1>) is not a button ;) I suggest to use something different.


You need to adjust your h1 click to do the following:

$("h1").click(function() {
    $(".foo").children().show();
});

Your .foo click is hidding the ul list which contains your .bar elements.

Example on jsfiddle.


The problem you're having is that this function:

      $(".foo").click ( function () {
          var obj = $(this);
          var children = obj.children();
          $(this).children().toggle (500);
      });

is hiding the UL items that contain your LI items, so even though you're calling $(".bar").show() they're not showing up, because their parent UL items are set to display:none.


try this:

$("h1").click ( function () {
              var subitems = $(".bar");
              $(".bar").parent().show();
          });

Hope it helps.


thats because you are hiding the ul instead of li when u click a foo :)

$(this).children().toggle (500); should be $(this).find('li.bar').toggle (500);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜