简体   繁体   English

Javascript:显示一个div的内容,使其他不可见

[英]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. 我正在尝试编写一个函数,该函数接受div的id,对照其他id的列表检查该id,显示与传入的id相关的div,并使列表中的id的所有其他div变为不显示。

<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. 不知道为什么这行不通-值得注意的是,我的ID是唯一的,所以我不认为这是问题所在。 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: 您可以使用querySelectorAll在这里提供帮助:

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: 我想知道何时将迭代器添加到NodeList接口,以便我们可以这样做:

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. 请注意,最好在'none'和''(空字符串)之间切换,以便该元素采用其默认或继承的样式,而不必对可能的内容进行硬编码。

Oh, without qSA: 哦,没有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 : 这取决于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';
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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