JavaScript get child element

后端 未结 3 1944
梦谈多话
梦谈多话 2020-12-13 08:56

Why this does not work in firefox i try to select the category and then make subcategory visible.



        
3条回答
  •  我在风中等你
    2020-12-13 09:51

    I'd suggest doing something similar to:

    function show_sub(cat) {
        if (!cat) {
            return false;
        }
        else if (document.getElementById(cat)) {
            var parent = document.getElementById(cat),
                sub = parent.getElementsByClassName('sub');
            if (sub[0].style.display == 'inline'){
                sub[0].style.display = 'none';
            }
            else {
                sub[0].style.display = 'inline';
            }
        }
    }
    
    document.getElementById('cat').onclick = function(){
        show_sub(this.id);
    };​​​​
    

    JS Fiddle demo.

    Though the above relies on the use of a class rather than a name attribute equal to sub.

    As to why your original version "didn't work" (not, I must add, a particularly useful description of the problem), all I can suggest is that, in Chromium, the JavaScript console reported that:

    Uncaught TypeError: Object # has no method 'getElementsByName'.

    One approach to working around the older-IE family's limitations is to use a custom function to emulate getElementsByClassName(), albeit crudely:

    function eBCN(elem,classN){
        if (!elem || !classN){
            return false;
        }
        else {
            var children = elem.childNodes;
            for (var i=0,len=children.length;i

    JS Fiddle demo.

提交回复
热议问题