开发者

Hiding all divs and showing one with jquery

I've looked around on the Stack for an answer that I could apply, but I'm not great with javascript.

I've got a list of links that need to show a hidden div. Easy enough. But there are about 8 of these links and the divs have to occupy the same space. 开发者_运维技巧Therefore, when you click on Link 1 (Link 1's div appears), and you then click on Link 2, I need Link 1's div to disappear and Link 2's div to appear.

Currently, I'm using jQuery's toggle function to get the effect I'm looking for, but you have to click the link twice to hide the info again.

Any ideas would be greatly appreciated!


Without having any syntax to work with, you should be able to use something like the following:

To Hide the links themselves:

//When a link is clicked...
$(".yourlink").click(function(){
     //Hide all of the links
     $(".yourlink").hide();
     //Show the selected link
     $(this).show();
});

likewise, if you wanted to use divs: (using the included HTML below)

//Javascript 
$(".link").click(function()
{
    $('div').hide();
    $('#'+$(this).attr('name')).show();   
});

//HTML
<a class='link' name='1'>Link 1</a>
<a class='link' name='2'>Link 2</a>
<a class='link' name='3'>Link 3</a>
<a class='link' name='4'>Link 4</a>
<a class='link' name='5'>Link 5</a>
<a class='link' name='6'>Link 6</a>
<a class='link' name='7'>Link 7</a>
<a class='link' name='8'>Link 8</a>

<div id='1'>1</div>
<div id='2'>2</div>
<div id='3'>3</div>
<div id='4'>4</div>
<div id='5'>5</div>
<div id='6'>6</div>
<div id='7'>7</div>
<div id='8'>8</div>

Working Demo


Instead of toggle, use .show() to display and .hide() to hide.


There are two simple approaches you could take in this situation.

  1. Utilize CSS to help toggle visibility.
  2. Utilize show() / hide() in jQuery.

The one I would suggest is utilizing CSS classes to help you accomplish your request. Create a class .showObject { display: block; } and another one .hideObject { display: none; }. Once you have the classes, you can utilize the jQuery functions addClass() and removeClass() to modify the display property.


    <a href="#" class="hider">link 1</a>
    <div id="div1" class="content" style="display:none;">
    </div>

    <a href="#" class="hider">link 2</a>
    <div id="div2" class="content" style="display:none;">
    </div>

    <a href="#" class="hider">link 3</a>
    <div id="div3" class="content" style="display:none;">
    </div>

    <a href="#" class="hider">link 4</a>
    <div id="div4" class="content" style="display:none;">
    </div>

    $(".hider").click(function(event){
        $(".content").hide();
        $(this).next().show();


    });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜