2015-06-18 77 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,而只是爲了獲得所需的效果。