How to toggle only the *next* .class or div (not the rest)

筅森魡賤 提交于 2019-12-24 00:15:18

问题


I was wondering how to toggle a "child" div only, clicking in a button which repeats over the html, like so :

<div class="button">
     <div class="hide toggle">
          Blah1
     </div>
</div>
<div class="button">
     <div class="hide toggle">
          Blah2
     </div>
</div>
<div class="button">
     <div class="hide toggle">
          Blah3
     </div>
</div>

The goal would be to affect only the inmediate child div, and keep hidden the rest.

I don't know if it's possible.

This bit of code was toggling me all of the divs :

<script type="text/javascript">
  $(document).ready(function(){

    $('.button').click(function() {
    $('.toggle').slideToggle();
    }, function () {
        $('.toggle').slideToggle();
    });

  });
</script>

Many thanks for your help.


回答1:


try

$(this).next('.toggle').slideToggle();

or

$(this).children('.toggle:first').slideToggle();



回答2:


Inside the click event handler the this keyword refers to the element that was clicked on. Replace your $('.toggle').slideToggle() lines with

$('.toggle',this).slideToggle();



回答3:


Thomas Stock and Russ Cam have it right... I just wrapped it up properly. Paste this onto your page somewhere... usually in the head or in the footer after all of your code.

<script type="text/javascript">
    $(document).ready(function(){ 
        $(".button").click(function() {
    $(this).next('.toggle').slideToggle();
    });
    });
</script> 



回答4:


what i have to do if my DIV that i want to toggle isn't child-element of the click-element, e.g:

<span onclick="$(this).next('.showme').slideToggle();">Klick to show first Showme-Class</span>
<div class="showme">You've clicked the first span-element</div>

<span onclick="$(this).next('.showme').slideToggle();">Klick to show second Showme-Class</span>
<div class="showme">You've clicked the second span-element</div>

<span onclick="$(this).next('.showme').slideToggle();">Klick to show third Showme-Class</span>
<div class="showme">You've clicked the third span-element</div>


来源:https://stackoverflow.com/questions/911328/how-to-toggle-only-the-next-class-or-div-not-the-rest

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