jQuery show/hide next div

天涯浪子 提交于 2020-01-11 03:33:09

问题


How do I show/hide next div? The following code works:

jQuery(".edittopic").click(function() {
    jQuery(this).next(".t_edit_cont").toggle();
});

... only if the t_edit_cont div is right after the edittopic button. Currently, I have them in separate DIVs, like this:

<div class="t_mod_box">
    <input type="submit" value="Edit" class="edittopic" name="send" /> 
</div>

<div class="t_edit_cont">
   Show hide content inside here...
</div>

How can I make this work? jsfiddle demo.


回答1:


You can use parent() to point jQuery in the right path:

jQuery(this).parent().next(".t_edit_cont").toggle();

Yet, a cleaner and more reliable approach would be to associate the clicked button and the div somehow.

For example (using data- attributes):

<input type="submit" value="Edit" class="edittopic" data-id="1" name="send" />

<div class="t_edit_cont" data-id="1">
Show hide content inside here...
</div>

Then:

jQuery(".edittopic").click(function() {
    var btnId = $(this).data('id');
    jQuery('.t_edit_cont[data-id=' + btnId + ']').toggle();
});    



回答2:


Need to select parent before doing .next()

DEMO

$(function() {
    $(".edittopic").on('click', function() {
        $(this).parent().next(".t_edit_cont").toggle();
    });
})



回答3:


I think so you want show hide as you want your FAQ, hopefully this is helpful for you

http://jsfiddle.net/indianwebdesigner/yhvm4duq/

if not then please leave a message

HTML

<div class="mod_wrap">
    <div class="t_mod_box">
        <a href="#" class="edittopic" name="send">Toggle</a>
    </div>

    <div class="t_edit_cont">
       Show hide content inside here... 1
    </div>
</div>

jQuery

$(this).parents(".mod_wrap").find(".t_edit_cont").slideToggle();


来源:https://stackoverflow.com/questions/27785890/jquery-show-hide-next-div

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