Toggle single div layer with jQuery

At runtime, I have a loop that creates a number divwith the same class depending on the number in the database.

<div class="show">....</div> 
<div class="show">....</div>  
<div class="show">....</div>  

I want to display this div using a function slideToggle()using jQuery. For each of them I have a separate hyperlink, which when clicked should display a div. There are also many tags between the hyperlink and the div that I want to switch.

<div>
<div>
<a href="#" class="display">View</a>  

</div>
    <br />
    </div>
    <div>
        <div class="clear"></div>
      </div>


<div class="show">....</div>

<div>
<div>    
<a href="#" class="display">View</a>  
</div>
    <br />
    </div>
    <div>
        <div class="clear"></div>
      </div>



<div class="show">....</div> 

<div>
<div>
<a href="#" class="display">View</a>  

</div>
    <br />
    </div>
    <div>
        <div class="clear"></div>
      </div>


<div class="show">....</div>   

$(function () {    
     $(".display").click(function(){    
         $(".show").slideToggle();    
         return false;     
      });  
});

Naturally, when it's called, each div layer is switched, no matter which hyperlink is clicked. I just want to switch the div closest to the given hyperlink.

Thanks in advance.

+3
source share
3 answers

<div> , this, , :

$(function () {
  $(".display").click(function () {
    $(this).next().slideToggle();
    return false;
  });
});

, , , .next(), , , <a>, (this), <div>, .

+2
$(function () {
  $(".display").click(function () {
  $(this).next.(".show").slideToggle();
  return false;
});
0

Or, when you create your divs, can you add (for example) a rel value that increments by one each time? I give you something like ...

<a href="#" class="display" rel="1">View</a>
<div class="show" rel="1">....</div>
<a href="#" class="display" rel="2">View</a>
<div class="show" rel="2">....</div>
<a href="#" class="display" rel="3">View</a>
<div class="show" rel="3">....</div>

This will then link the two divs so that you can get the rel value of your clicked element and use it to identify the shown / hidden div.

<script type="text/javascript">
$(function () {
$(".display").click(function () {
var element_id = $(this).attr('rel');
$(".show").attr('rel', element_id).slideToggle();
return false;
});
});
0
source

Source: https://habr.com/ru/post/1777453/


All Articles