expanding and collapsing folders

让人想犯罪 __ 提交于 2019-12-13 05:57:53

问题


I need to get more than one element to toggle open and closed. Right now the function is just selecting the ID, but I'd like to know how to get it to select a class. I thought I could change the document.getElementById to document.getElementByClass but that didn't work.

I picked this bit of code during my search:

#ToggleTarget {display:hidden;}

<script type="text/javascript">
function Toggle() {
    var el = document.getElementById("ToggleTarget");
    if (el.style.display == "block") {
        el.style.display = "none";
    }
    else {
        el.style.display = "block";
    }
}
</script>

回答1:


var getElementsByClassName = function(node, classname) {
    if (document.getElementsByClassName) { 
        return document.getElementsByClassName(classname);
    }
    var a = [];
    var re = new RegExp('(^| )'+classname+'( |$)');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

var Toggle = function(){
    var tp = getElementsByClassName(document.documentElement,'toggle');
        for(var i = 0; i < tp.length; i++){
            if(tp[i].style.display=='none')
                tp[i].style.display='block'
            else
                tp[i].style.display='none'
    }
}

Use getElementsByClassName and then loop through them.

EDIT

Just make sure they have the class toggle as used in my code above.

UPDATE

Added function for IE support (adopted from https://stackoverflow.com/a/7410966/600101).



来源:https://stackoverflow.com/questions/12386060/expanding-and-collapsing-folders

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!