简体   繁体   中英

Javascript: Display contents of one div, make others invisible

I'm trying to write a function that takes in an id of a div, checks that id against a list of other ids, displays the div relevant to the passed-in id, and causes all other divs for the ids in the list to not be displayed.

<script type="text/javascript">
function display_page(id) {
//list of ids that I want to check against
   var pages = ['home', 'about', 'listen', 'more']; 
    for (var i=0; i<pages.length; i++) {
        var e = document.getElementById(pages[i]);
        if (pages[i] == id){
            e.style.display = 'block';
            alert(e);
        } 
        else{
             e.style.display = 'none';  
            alert(e);
        }
    }
</script> 

And my function calls are structured like this:

<li class="active" class="test"><a href="#" onclick="display_page('home');">Home</a></li>

Not sure why this isn't working -- as a note, my ids are unique so I don't think that's the issue. The alerts are not showing up though upon clicking the relevant links (like the one posted above). Thanks for the help!

You can use querySelectorAll to help here:

function display_page(id) {

    var pages = document.querySelectorAll('#home, #about, #listen, #more');

    for (var i=0, iLen=pages.length; i<iLen; i++) {
      pages[i].style.display = pages[i].id == id? '' : 'none';
    }
}

I wonder when an iterator will be added to the NodeList interface so we can do:

var id = 'home';
document.querySelectorAll('#home, #about, #listen, #more').forEach(function(el) {
    el.style.display = el.id == id? '' : 'none';
});

Note that toggling between 'none' and '' (empty string) is preferred so that the element adopts its default or inherited style and you don't have to hard–code what that might be.

Oh, without qSA:

function display_page(id) {
    var ids = ['home', 'about', 'listen', 'more'];

    for (var i=0, iLen=ids.length; i<iLen; i++) {
      page = document.getElementById(ids[i]);
      page.style.display = page.id == id? '' : 'none';
    }
}

This one depends on ES5 forEach :

function display_page(showId) {
    ['home', 'about', 'listen', 'more'].forEach(function(id) {
        var page = document.getElementById(id);
        page.style.display = page.id == showId? '' : 'none';
    });
}

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