Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
613 views
in Technique[技术] by (71.8m points)

html - Show one div while hiding other divs with jquery when clicking on links

I am trying to create a navigation scheme that has a series of links and number of divs. When I click on link 1 I want to show div 1. If I click on link 2 I want to hide 1 and show 2 etc.

I was able to get the following code to work. However, what is happening is when any other link on the page is clicked the div that is currently being displayed disappears/hides.

I have tried various solutions but have been unable to figure this out. Can someone provide some insights to what may be happening based on the code below.

HTML:

    <ul id="navigation">
        <li data-tab="property" class="activeitem settingLink active"><a href="#">Property Flyers</a></li>
        <li data-tab="openhouse" class="settingLink"><a href="#">Open House Flyers</a></li>
        <li data-tab="postcards" class="settingLink"><a href="#">Postcards</a></li>
        <li data-tab="mortgage" class="settingLink"><a href="#">Mortgage Flyers</a></li>
        <li data-tab="recruiting" class="settingLink"><a href="#">Recruiting Flyers</a></li>
    </ul>


    <div id="property" class="span-18 last"><img src="images/templates/thumbs/property84.jpg" width="143" height="194" /></div>
    <div id="openhouse" class="span-18 last"><img src="images/templates/thumbs/property84.jpg" width="143" height="194" /></div>
    <div id="Postcards" class="span-18 last"><img src="images/templates/thumbs/property84.jpg" width="143" height="194" /></div>
    <div id="Mortgage" class="span-18 last"><img src="images/templates/thumbs/property84.jpg" width="143" height="194" /></div>
    <div id="Recruiting" class="span-18 last"><img src="images/templates/thumbs/property84.jpg" width="143" height="194" /></div>

JavaScript:

$('a').on('click', function(e) {
    e.preventDefault();
    var $li = $(this).closest('li');

    var tab = $li.data('tab');
    var current = $('.active.settingLink').data('tab');

    $('#' + current).fadeOut('fast', function() {
        //Slide the new div down
        $('#' + tab).fadeIn();
    });

    //Remove active class from current link
    $('.active.settingLink').removeClass('active');

    $li.addClass('active');
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

$('a') targets every <a> tag in page, you need more specific selector:

$("#navigation a');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...