开发者

on jQuery: with a lot of items show only div of this anchor clicked

开发者 https://www.devze.com 2022-12-10 19:03 出处:网络
first of all: sorry for my english i have a webpage like this <div class=\"item\"><div class=\"details\">

first of all: sorry for my english

i have a webpage like this

<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 click on 'a' it shows me the relative 'div' for ALL items. Id like if i click on first 'a' of the first element it shows me the first 'div' of the first ONLY item, not all items.

here's a test page link text (:O it works only with links on first div!)

I hope to have been clear..

Thanks all


If you're able to add a class attribute to the divs and links.

<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>

Then, your jQuery can be as simple as:

$(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
       });
    });


EDIT, ouch! the INDEX was messing it up, div:eq(' + index + ') was always looking for the first, second and third elements of the first item div, try this:

$(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();
    });
  });
});

And try to incorporate a simpler solution, like @Dave Beer's.

0

精彩评论

暂无评论...
验证码 换一张
取 消