开发者

Newbie Toggle question

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜