jQuery parent().find() problem

这一生的挚爱 提交于 2019-12-06 21:01:18

问题


HTML

<div class="comments">
    <a class="toggle" href="#">Toggle Comment 1</a><br />
    <div class="comment" style="display:none;">
        Comment1
    </div>
    <hr />
    <a class="toggle" href="#">Toggle Comment 2</a><br />
    <div class="comment" style="display:none;">
        Comment2
    </div>
</div>

JavaScript

$(function(){
    $('.toggle').click(function() {
        $(this).parent().find('.comment').slideToggle();
        return false;
    });
});

Can be viewed here: http://jsfiddle.net/saiprex/ESM4m/

How i can toggle comment that's been clicked and not all of them?

Cheers, Pav


回答1:


$(function(){
    $('.toggle').click(function() {
        $(this).nextAll('.comment:first').slideToggle();
        return false;
    });
});

jsFiddle.




回答2:


its even simpler, I think, when you clean up your html as well a little bit: (avoid br)

http://jsfiddle.net/ESM4m/27/

<div class="comments">
    <a class="toggle" href="Fork#">toggle</a>
    <div class="comment" style="display:none;">
        Comment1
    </div>
    <hr />
    <a class="toggle" href="#">toggle</a>
    <div class="comment" style="display:none;">
        Comment2
    </div>
</div>




$(function(){
    $('.toggle').click(function() {
        $(this).next().slideToggle();
        return false;
    }); 
});


来源:https://stackoverflow.com/questions/5972618/jquery-parent-find-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!