On jQuery: with a lot of elements, only the div of this anchor pressed is displayed

first of all: sorry for my english

I have such a web page

<div class="item"><div class="details">
<ul>
<li><a href="#">Show div 1</a></li>
<li><a href="#">Show div 2</a></li>
<li><a href="#">Show div 3</a></li>
</ul>
<div>div 1</div>
<div>div 2</div>
<div>div 3</div>           </div></div>

IMPORTANT: I ​​have several divs called "item".

I have this jquery script

$(document).ready(function() {
  $('ul > li > a').each(function(index) {
  $(this).click(function() {
  $('.details > div:eq(' + index + ')').toggle()
  .siblings('.details > div').hide();
  });
  });
});

BUT, if I press "a", it will show me the relative "div" for ALL items. Id, as if I pressed the first "a" of the first element, it showed me the first "div" of the first ONLY, and not all elements.

here is the test page link text (: O only works with links to the first div!)

I hope it was clear.

Thank you all

+3
source share
2 answers

, ! INDEX , div:eq(' + index + ') , div, :

$(document).ready(function() {
  $('ul > li > a').each(function(index) {
    $(this).click(function() {
        $(this).closest('.item').siblings().find('.details > div').hide();
        $('.item .details div:eq(' + index + ')').toggle();
    });
  });
});

, , @Dave Beer's.

+2

div .

<div class="item"><div class="details">
<ul>
<li><a href="#" id="div1">Show div 1</a></li>
<li><a href="#" id="div2">Show div 2</a></li>
<li><a href="#" id="div3">Show div 3</a></li>
</ul>
<div class="div1">div 1</div>
<div class="div2">div 2</div>
<div class="div3">div 3</div>           </div></div>

jQuery , :

$(document).ready(function() {
  $('ul > li > a').click(function(){
          $('#details > div').hide(); // hide all of the divs
          $('div.' + this.id).show(); // then show the one with the same class as the link.id that was clicked
       });
    });
+2

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


All Articles