简体   繁体   中英

this.id not working in ie

I've been putting together an accordion-style left-navigation using JavaScript, and I've run into a problem where the following code works in Chrome and Firefox but not in IE.

function navClick(clickedDD){
    var numDD = document.getElementsByClassName('navDropdown');
    var numArrow = document.getElementsByClassName('navUnfolded');
    var selectedDD = document.getElementById('dd0' + clickedDD);
    var arrow = document.getElementById('arrow0' + clickedDD);
    if (selectedDD.style.display == 'none') {
        for (var i = numDD.length - 1; i >= 0; i--) {
            numDD[i].style.display = 'none';
        }
    }
    if (arrow.className == 'navFolded') {
        for (var i = numArrow.length - 1; i >= 0; i--) {
            numArrow[i].className = 'navFolded';
        }
    }
    if (selectedDD.style.display == 'none') {
        selectedDD.style.display = 'block';
        arrow.className = 'navUnfolded';
    } else {
        selectedDD.style.display = 'none';
        arrow.className = 'navFolded';
    }
}

I'm not positive what's keeping it from functioning, but I suspect it's the "this.id" I'm using in the onclick.

<div id="1" onclick="navClick(this.id);">Content</div>

I'm relatively new to JavaScript, if that's helpful to know. Basically, this function first looks to see if the clicked div is displayed or not, and if not then it sets display to none for all the divs before continuing. If it is displayed, it does nothing because the next bit will handle it. There's a similar rule right after for divs with an arrow image that changes. Then if it the div is not displayed, it sets it to 'block' or else it sets it to 'none', which allows me to open and close a single menu div without opening/closing the others.

I'm using the id collected by the onclick function to control a div with a different id, as can be seen in the bottom to variables at the top of the function. Perhaps this is where IE is getting touchy.

Any help is appreciated.

On your element, try puttin the ID in quotes:

<div id = '1' onClick="navClick(this.id);">

You could also try using javascript's 'Alert' function to find out what the data looks like in IE:

alert(selectedDD); 

getElementsByClassName isn't supported in IE8 or below.

You could try Jonathan Snook's approach for IE8 and below compatibility if you don't want to use a full library.

Your id in <div id="1" .. is not a valid one:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

so try changing it for valid one (eg. #a1 ) as that may be the cause of your problem.

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