Java Script Validator指示“不要在循环中创建函数”

时间:2018-04-26 18:41:19

标签: javascript

我对Javascript很新,我试图在一个页面内创建多个模态图像。我在下面生成了这个编码

// create references to the modal...
var modal = document.getElementById('myModal');
// to all images
 var images = document.getElementsByClassName('visual');
  // the image in the modal
 var modalImg = document.getElementById("img01");

 // Go through all of the images with our custom class
 for (var i = 0; i < images.length; i++) {
  var img = images[i];
  // and attach our click listener for this image.
  img.onclick = function (evt) {
console.log(evt);
modal.style.display = "block";
modalImg.src = this.src;
 }
}
 // When the user clicks anywhere outside of the modal, close it
 window.onclick = function(event) {
   if (event.target == modal) {
       modal.style.display = "none";
   }
}

它声明第12行“不要在循环中创建函数”。非常感谢帮助解决这个问题。

1 个答案:

答案 0 :(得分:0)

您可以在循环外部定义img.onclick处理程序一次命名函数:

List<Answer> userAnswers = answers.stream()
        .filter(answer -> users.stream().anyMatch(user -> 
             user.answerCode==answer.code))
        .collect(Collectors.toList());