开发者

How can I show div on click, hide the others with jQuery?

I'd like to have a text area on my page that shows a div and hides the others (let's say 8 other divs). On click, I'd like the chosen div to show and the c开发者_StackOverflow中文版urrent div & other divs to hide. Is there a simple solution to this? Possible to build off of: show current clicked div hide previous clicked div ?


Here's a simple solution making use of chaining together methods.

$("input").click(function () 
{
    $("#" + $(this).attr("class")).show().siblings('div').hide();
});

jsFiddle example ( using $("input") )
jsFiddle example ( using $(".className") )

The activating buttons could have the same class as the id of the affected divs, or you can use a separate "toggler" class.

The important part is to use a unique feature of the clicked element to map to a unique feature of the toggled element.

Finally, if the toggling divs are not siblings, you can set up a selector of all of them using var divs = $("#blah1, #blah2, #blah3, ..."); and toggle them using .not().

jsFiddle example of non sibling toggling divs using .not()


How about something like this?

$(document).ready( function(){
  $('div.some_class').click( function(){ // set of divs to be clickable
    $(this).siblings('div').hide(); // it's already showing, right?
  });
});

Of course, once one is clicked and the others are hidden, you'll have no way of bringing them back...


it depends on the DOM structure. I'd personally give them some class to have an easy access to the whole group. $('.div-group').hide(0, function(){$('#my-div').show();});

Consider using jQuery UI Accordion, which might be an answer to functionality you need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜