jQuery只切换一个元素,而不必使用id [英] jquery only toggle one element without having to use ids

查看:79
本文介绍了jQuery只切换一个元素,而不必使用id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面上有多个具有相同类的div.我希望能够单独切换它们.使用此脚本:

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

HTML如下所示:

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

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

现在,如果我单击任一链接,它将在页面上切换两个div(该页面最终将具有多达10个可切换的div.我知道我可以向每个div添加ID,但是我不想为每个ID编写一次jquery脚本.

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.

我对jquery还是很陌生,所以我确定有一种简单的方法可以做到这一点.我尝试使用.closest('div'),但这也不起作用.

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.

有帮助吗?

推荐答案

也许您可以尝试以下方法:

Maybe you could try with this:

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

这是一个示例: http://jsfiddle.net/6GRJr/

这篇关于jQuery只切换一个元素,而不必使用id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆