javascript - 使用 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)
解决方案
.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 循环以及您的索引问题。
推荐阅读
- javascript - 如何使用 esprima 解析来自 Java 的 javascript 文件?
- c++ - ESP8266 NtpClient 将 int 响应解析为 char* 2 位数字
- r - Keep only specific strings in a column, otherwise convert to NA
- bash - 循环中的 Bash 变量名扩展
- php - Laravel Excel Maatwebsite - SUM 函数不起作用
- go - 使用接口来使用不同包中的方法
- node.js - Mongoosastic:TypeError:无法读取未定义的属性“toLowerCase”
- python - 如何在等待输入时保持终端更新?
- reactjs - 如何在反应中显示餐厅开放或关闭的状态
- android - 将数据发送到 api 时,Json 数组正在转换为字符串。如何删除它?