开发者

Click events on Multiple divs and elements

开发者 https://www.devze.com 2023-02-03 14:28 出处:网络
Im brand new to jQuery and i\'ve hit a block!, 1st ill decsribe me document and what im hoping to achieve.

Im brand new to jQuery and i've hit a block!, 1st ill decsribe me document and what im hoping to achieve.

I have a set of buttons (6) that ech call in a different div with content using the .fadeIn event. when the document loads, the initial 开发者_StackOverflow中文版div is visible aht the other 5 are hidden using <div style="display:none".....>.

What i need help with is how to use the .click function on each button to hide ALL div exect the one clicked by the user. I hope this makes sense. my code as far as i could understand looks line this:

$(document.ready(function() {
    $("#my1stbutton").click(function() {
        $("#my1stdiv").fadeIn();
    });
});

this is successfully showing "#my1stdiv" but after that, i dont know how to code such that when i click on "#my2ndbutton" the action hides "#my1stdiv" and displays "#my2nddiv" and so on.

Please help. Otherwise im loving jQuery...

regards


First, you need to give your elements classes as well as IDs. This means you can select multiple elements in one go. So your links could have the class button and your div elements the class section.

You should also know that, within an event handler, the variable this is the element that was clicked on.

First, we will find the element with the class section that is visible. We can then use the function index, which tells us which element in the set was clicked on, and use this to work out which element to show.

$(document).ready(function(){
    $('.button').click(function() { // when a button is clicked
        $('.section:visible').fadeOut(); // hide the visible section
        $('.section').eq($(this).index()).fadeIn(); // show the section that has the equivalent position in the set to the link 
    });
});


try this...

$("#button1").click(){
    $("#div1").fadeIn();
    $("#div2").css("display", "none");
    $("#div3").css("display", "none");
    ..all other divs you want to hide
});

you can also do .hide() on the divs

$("#button1").click(){
    $("#div1").fadeIn();
    $("#div2").hide();
    $("#div3").hide();
    ..all other divs you want to hide
});


or maybe what you need is UI accordion ?


Try

$('button').click(function(){
    $(this).parent('div').fadeIn();
    $('div').not($(this).parent('div')).toggle('fast');
});

EDIT:

$('button').click(function(){
    var index = $('button').index(this);
    $('div').eq(index).fadeIn();
    $('div').not('nth-child:' + index - 1).toggle('fast');  //0 To 1 based
});
0

精彩评论

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