简体   繁体   中英

AddEventListener function variable scope issue in IE 11

I have a function that works fine in Chrome, but testing in IE, it cannot access the variable outside of the function:

if (cipher[i].solved == false){
    bottom.classList.add("HighlightBox");            
    bottom.classList.add("bg-warning");
    bottom.addEventListener('click', function(){
        // IE cannot access cipher[i] in this function
        cipher[i].solved = true;
        hintsUsed++;
        runHint(true);
        populateAnswerKey(puzzleWord, cipher, false);
        populatePuzzleBoard(puzzleWord, cipher);

    });
} 

cipher[i] is not able to be accessed by IE (though it works fine in Chrome). Is there a way to pass cipher[i] through, or another easy adjustment I can make so that IE can access that variable when it creates the event listener?

EDIT : After more testing, it seems that the issue is that IE does not retain the value of the iterator [i]. It always remains one higher than the final pass through regardless of which event is clicked. Chrome can retain the iterator's value.

EDIT2 : https://www.dan-teacher.com/cryptogram/41SXLPS1 - This is the game. It works in Chrome, but fails in (my version) of IE when I click "Use Hint" and then click one of the boxes.

let statement in loop doesn't work as expected in IE

"let" has issues in Internet Explorer. The simple workaround was to change:

for (let i = 0, i < cipher.length; i++){
    // code  
} 

to

for (let k = 0, k < cipher.length; k++){
    let i = k;
    // code  
} 

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