简体   繁体   English

这在香草JavaScript循环?

[英]this within a loop in vanilla javascript?

Im making a quiz. 我正在测验。 I need to loop through an array of options which are <li> and add a click event listener to the correct answer. 我需要遍历为<li>的选项数组,并将click事件侦听器添加到正确的答案。 In the code below the correct answer is 5 but in reality it will change. 在下面的代码中,正确答案是5,但实际上它将改变。 So I need to add the click event listener to the 5th <li> . 因此,我需要将click事件监听器添加到第五个<li>

var someFunction = function() {
    var correctAnswerNo = "5";
    var options = optionsContainer.getElementsByTagName("li");

    for (var i = 0; i < options.length; i++) {
        console.log(i);
        console.log(correctAnswerNo);
        if (correctAnswerNo === i) {
            console.log(this);
            // here is where I will put my event listener 
        }
    }
}

When I log out correctAnswerNo and i it works as expected. 当我退出correctAnswerNoi它按预期工作。 However when I log this then I get undefined. 但是,当我记录this然后我不确定。 I need to access this to add the click event to it. 我需要访问this才能向其中添加click事件。

Rather than adding event listener to this , add it to options[i] inside the if 而不是增加事件侦听器向this ,将其添加到options[i]if

Your if condition will be something like if条件将会像

if (correctAnswerNo === i) {
  options[i].addEventListener("click", function() {
    console.log("correct answer");
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM