0

I have a for loop that dynamically adds a listener to a div layer. I need to add a different parameter dependant upon the div that is clicked and the content inside the divs is also generated dynamically from and external source. That part all works fine it's just the listener that adds the same parameter to each div no matter what comes out of the JSON.

for (i=0; i<4; i++) {
    var answerBox = 'answer' + (i + 1);
    app.LoadInnerHTML(answerBox, answers[i].title);
    var answerIndex = answers[i].index;
    var answerElement = document.getElementById(answerBox);
    if (answerElement.addEventListener) {  // all browsers except IE before version 9
        answerElement.addEventListener("click", function () {
            thisQuiz.AnswerQuestion(answerIndex);
        }, false);
    } else {
        if (answerElement.attachEvent) {   // IE before version 9
            answerElement.attachEvent("click", function () {
                thisQuiz.AnswerQuestion(answerIndex);
            });
        }
    }
} 

When I debug the code the answerIndex is different each loop, but by the time I click the answer it's changed all the indexes to 2.

Web Develop Wolf
  • 5,996
  • 12
  • 52
  • 101

0 Answers0