SlideToggle div不起作用

时间:2016-02-09 08:50:10

标签: jquery

我有这段代码:

$('.close-button').click(function() {
	$(this).closest('#hidden').slideToggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="bloc">
  <h2>Click on that link to display the content <a href="#" class="close-button">Click here</a></h2>
  <div id="hidden">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus augue ante, fringilla ac sodales et, vehicula pellentesque ante. Integer id mattis erat, nec tincidunt nisi. </p>
  </div>
</div>

<div class="bloc">
  <h2>Click on that link to display the content <a href="#" "close-button">Click here</a></h2>
  <div id="hidden">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus augue ante, fringilla ac sodales et, vehicula pellentesque ante. Integer id mattis erat, nec tincidunt nisi. </p>
  </div>
</div>

当您点击该链接时,会显示div #hidden

我尝试在Jquery中执行此操作,但它不起作用。

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

首先获取parent元素,然后获取next元素:

$('.close-button').click(function() {
    $(this).parent().next().slideToggle();
});

要注意:closest方法获取元素最接近的父元素。

答案 1 :(得分:1)

请勿使用重复的id,而是使用class

.closest只能通过父母查询,而不是父母的兄弟姐妹。

&#13;
&#13;
$('.close-button').click(function() {
	$(this).parent().next().slideToggle();
});
&#13;
.hidden{
    display:none;
  }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="bloc">
  <h2>Click on that link to display the content <a href="#" class="close-button">Click here</a></h2>
  <div class="hidden">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus augue ante, fringilla ac sodales et, vehicula pellentesque ante. Integer id mattis erat, nec tincidunt nisi. </p>
  </div>
</div>

<div class="bloc">
  <h2>Click on that link to display the content <a href="#" class="close-button">Click here</a></h2>
  <div class="hidden">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus augue ante, fringilla ac sodales et, vehicula pellentesque ante. Integer id mattis erat, nec tincidunt nisi. </p>
  </div>
</div>
&#13;
&#13;
&#13;