2015-06-18 59 views
2

我有这个代码的slideToggle多个div

jQuery(function ($) { 
 

 
//After it toggle the content with this button 
 
$('.content_toggle').hide(); 
 

 
$(".link-toggle").click(function() { 
 
$(this).nextAll(".content_toggle").slideToggle("slow"); 
 
}); 
 

 

 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> 
 
<div class="link-toggle">Read more</div> 
 
<div class="content_toggle"> 
 
    Hello world 
 
</div> 
 

 
<div class="link-toggle">Read more again ?</div> 
 
<div class="content_toggle"> 
 
    Another Hello world 
 
</div>

我想通过一个切换这些内容之一, 就像当我点击第一个div,其内容如下切换。 然后如果点击第二个div,它的下面的内容切换。

不是两个在同一时间。

回答

1

给他们的ID和使用它们的ID您nextAll切换

jQuery(function ($) { 

//After it toggle the content with this button, and use next instead of nextAll 
$('.content_toggle').hide(); 

    $("#myfirstDiv").click(function() { 
      $(this).next(".content_toggle").slideToggle("slow"); 
    }); 
    $("#mysecondDiv").click(function() { 
      $(this).next(".content_toggle").slideToggle("slow"); 
    }); 



}); 
3

更改到下一个仅定位到紧随其后的类不能低于它

$(this).next(".content_toggle").slideToggle("slow");

1

每堂课
<div> 
    <div class="link-toggle">Read more</div> 
    <div class="content_toggle"> 
     Hello world 
    </div> 
</div> 

in a <div>

然后使用siblings方法:

$(".link-toggle").click(function() { 
    $(this).siblings(".content_toggle").slideToggle("slow"); 
    }); 
}); 
1

不要使用nextAll,只需使用next

jQuery(function ($) { 
 

 
//After it toggle the content with this button 
 
$('.content_toggle').hide(); 
 

 
$(".link-toggle").click(function() { 
 
$(this).next(".content_toggle").slideToggle("slow"); 
 
}); 
 

 

 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> 
 
<div class="link-toggle">Read more</div> 
 
<div class="content_toggle"> 
 
    Hello world 
 
</div> 
 

 
<div class="link-toggle">Read more again ?</div> 
 
<div class="content_toggle"> 
 
    Another Hello world 
 
</div>

1

它做什么,你说,它应该做的。这个“nextAll”将在所有后续的兄弟姐妹中执行该动作。请参阅文档:https://api.jquery.com/nextAll/

不要使用nextAll,而只是为了获得所需的效果。