开发者

jquery only toggle one element without having to use ids

i have multiple divs with the same class on my page. I want to be able to toggle them individually. Using this script:

 $(document).ready(function() {
   $('.file').hide();

   $('a.toggle').click(function() {
      $('.file').slideToggle(1000);
      $(this).text($(this).text() == 'show' ? 'hide' : 'show');
      return false;
   });
 });

the HTML looks like this:

<div class="file-wrapper">
 <h5>(<a href="#" class="toggle">show</a>)</h5>
  <div class="file">
   <?php require "lipsum.php"; ?>
  </div><!-- .file -->
</div><!-- .file-wrappe开发者_JAVA百科r -->

<div class="file-wrapper">
 <h5>(<a href="#" class="toggle">show</a>)</h5>
  <div class="file">
   <?php require "lipsum.php"; ?>
  </div><!-- .file -->
</div><!-- .file-wrapper -->

Now if i click either of the links it will toggle both divs on the page (the page will ultimately have up to 10 toggleable divs. I know i could just add IDs to each div, but i don't want to have to write the jquery script once for each id.

I'm fairly new to jquery so I'm sure there is a simple way to do this. I've tried using .closest('div') but that isn't working either.

Any help?


Maybe you could try with this:

$(this).parent('h5').next('div.file').slideToggle(1000);

Edit: Here's an example: http://jsfiddle.net/6GRJr/


this is because it's always hiding all your divs with class file do it like this

$(document).ready(function() {
   $('.file').hide();

   $('a.toggle').click(function() {
      $('div.file', this.parentNode).slideToggle(1000);
      $(this).text($(this).text() == 'show' ? 'hide' : 'show');
      return false;
   });
 });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜