views:

208

answers:

2

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

A: 

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.

karim79
OH!It was my fault! I was using jQuery 1.3. I tryed to use last version (1.3.2) and now it works (with my first code!) (http://www.oakabilly.com/test/test3.html)I didnt know it was so different.Really thanks for your time.
oakabilly
Perhaps you should post that as an answer and flag it as the correct one?
Morningcoffee
+1  A: 

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
       });
    });
davewasthere
thanks.but id like to not use other classes or divs (ive already some classes i used for css-background). i know there is a way because until some days it was working..then i changed something.. :|
oakabilly