jQuery slideToggle one div at a time instead of all independently

本小妞迷上赌 提交于 2019-11-29 11:27:56

Just close them all up again every time one is clicked:

jQuery(document).ready(function($) {
$(".entry-content").hide('slow');
$(".entry-title").click(function() {
    $(".entry-content").hide();
$(this).parent().children(".entry-content").slideToggle(500); });
});

Example: http://jsfiddle.net/auUxk/

Yes, you can just use this logic:

$(".entry-title").click(function() {
    // hide all entry title elements
    $('.entry-title').hide();
    // show the clicked one
    $(this).show();
});

You can adjust it to use toggle instead of hide/show.

I am usually doing this kind of logic by assigning special css classes to elements (its better to have things separated). So when I click element, I add a class to it. But then, when you click another element, you have to elements with that class, but you want only one. So you have to modify it. First remove that class from all elements with it, and then add it to clicked element.

$(".anyAffectedElement").click(function() {
    // remove any instances of special class
    $('.enabledElement').removeClass('eneabledElement');
    // add special class to clicked element 
    $(this).addClass('enabledElement');
});

^ This is just a general logic how can you deal with things like this. In simple cases, that 'enabledElement' class just adds some special styling (like highlight).

Igor Laszlo

I did not understand those examples which were given by others, but finally i have found the answer in another place, if anyone needs a solution simplier (or different) : http://jsfiddle.net/bipen/zBdFQ/1/

@markratledge - first you need to give id of your divs instead of classes...

$("#link1").click(function(e) {
  e.preventDefault();
  $("#div1").slideDown(slow);
  $("#div2").slideUp(slow);
});

$("#link2").click(function(e) {
  e.preventDefault();
  $("#div1").slideUp(slow);
  $("#div2").slideDown(slow);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!