首页 > 解决方案 > 使用 javascript/jQuery 陷入索引 5 的 For 循环迭代

问题描述

我正在为我正在学习的课程的初学者项目构建连接四。我无法让它在过去的索引 5 上移动。似乎仍然返回 true 索引 5 未定义,即使在我第一次单击它之后,它已经变成红色。我认为它会在每次单击后运行 for 循环,再次从 5 开始,但它会返回 False,然后返回到下一个索引 4,检查那个,等等。我查了很多,我只是卡住了。我想不通。

我知道从游戏的长远来看,代码并不完整;我只是想理解这一步,不管代码有多难看,这样我就可以继续进行另一部分了。

    var gClass = $(".G")

function returnBackgroundColor(rowIndex,colIndex){
  // console.log($(colIndex[rowIndex]).prop("background-color"));
  // console.log(rowIndex);
  return($(colIndex[rowIndex]).prop("background-color"));
}

function changeColor(row, someClass){
  someClass.eq(row).css("background-color","red");
}

function checkColor(someClass){
  someClass.click(function() {
    for (var row = 5; row > -1; row--) {
      if (returnBackgroundColor(row, someClass) === undefined){
        console.log(row);
        return changeColor(row, someClass);
      }else {
        console.log("False");
      }
    }
  })
}

checkColor(gClass)

标签: javascriptjqueryiterationlogic

解决方案


.G不要在每次单击时循环遍历所有具有类名的元素,而是尝试$(this)在单击函数中使用 jQuery 关键字。像这样:

function addClickListener(someClass){
   $(someClass).each(function () {
      this.addEventListener('click', function() {
          // an example of how you use the $(this) 
          $(this).addClass('background-color-red');
      });
  });​
}

这样,您将摆脱该 for 循环以及您的索引问题。


推荐阅读