简体   繁体   中英

Javascript to show/hide specific divs in a group

I have searched extensively for scripts that toggle the display of an element, but can't find one that suitably does the job for the following:

On my webpage I have several sections of content for instance..

    <div id="section1">
        <div id="section1a" class="section1links"></div>
        <div id="section1b" class="section1links hide"></div>
        <div id="section1c" class="section1links hide"></div>
    </div>

    <div id="section2">
        <div id="section2a" class="section2links"></div>
        <div id="section2b" class="section1links hide"></div>
        <div id="section2c" class="section1links hide"></div>
    </div>

By default, the first div in a section is displayed, hence the class names and I have the following CSS:

    .hide {
        display: none;
    }

I then have a link for example, which is to show 'section1b':

    <a href="#" onclick="show('section1links','section1b')">show section 1b</a>

In this instance, I then need a javascript function, that would first remove the 'hide' class name from all elements with class 'section1links', then add it to all elements except 'section1b'.

Simply put:

    function show(group, sectiontoshow)
    {
        get elements with class name 'group'
        remove any instances of class name 'hide' wherever present

        add class name 'hide' to all elements with class name 'group', except the one with id 'sectiontoshow'.
    }

Also, when a link is clicked on it musn't make the webpage jump back to top. I would usually use 'javascript:void(0)' in the link rather than a hashtag, but don't know whether it would cause a conflict.

I am sure you more qualified JS programmers might have a better solution and might think this is a very longwinded effort, I am more designer, but any help whatsoever would be appreciated.

do you use jQuery already, if not: use it - then you can do the following:

$('.group').removeClass('hide').not('#sectiontoshow').addClass('hide');

in your function the code should be used like this:

function show(group, sectiontoshow) {
  $('.' + group).removeClass('hide').not('#' + sectiontoshow).addClass('hide');
}

Passe the id of your element and the class you want it to have than use the id to change its class to the class you passed in parameter.

function Show(Class, Id)
{
    document.getElementById(Id).className = Class;
}

For this to work you need your a to be like this:

<a href="#" onclick="show('section1links','section1b')">show section 1b</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM