开发者

Newbie Toggle question

开发者 https://www.devze.com 2023-02-26 06:36 出处:网络
What am I missing here? When I click on the \'h2 a\' link, the .content ol should toggle. I can\'t figure out why it isn\'t working :(

What am I missing here? When I click on the 'h2 a' link, the .content ol should toggle. I can't figure out why it isn't working :(

<script type="text/javascript">
$(document).ready(function(){
$(".content ol").hide();
$(".content h2 a").click(function(){
$(this).find(".content ol").toggle(400);
});
});
</script>

  <div class="content"> 
    <h2><a href="#">click me</a></h2>
    <ol>
      <p>Some text</p>
    </ol> 
  <开发者_JAVA百科/div>


The problem is that find looks for elements that are descendants of the current selected eleemnt. You are looking within this, which is the link that was clicked on. Obviously, the ol is not within the a element.

You need to use closest, to go up the tree to the div and only then use find:

$(".content h2 a").click(function(){
    $(this).closest('.content').find("ol").toggle(400);
});


@andy, I've created a jsfiddle that cleans up the slide a bit for you. Should work across all modern browsers.

http://jsfiddle.net/9QgmQ/3/

$(document).ready(function(){
    $(".content ol").hide();
        $(".content h2 a").click(function(){
        $('.content').find(" ol").slideToggle(400);
    });
});

You may want to consider using $.(object).slideToggle() instead of toggle(), for a smooth up/down toggle.

0

精彩评论

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