使用JavaScript/jQuery陷入索引5的For循环迭代 [英] Stuck in For loop iteration of index 5 using javascript/jQuery
问题描述
我正在为我所修课程的每个初学者项目构建四连环".我无法让它继续移动到过去的索引5.即使我第一次单击它后,它仍变成红色,但似乎仍返回true索引5未定义.我认为它会在每次单击后运行for循环,再次从5开始,但是它将返回False,然后返回到下一个索引4,检查该索引,依此类推.我抬头很多,只是被卡住了.我不知道.
I'm building Connect Four per my beginner's project for the course I'm taking. I can't get it to move on past index 5. It seems to still return true that index 5 is undefined, even though after I click it the first time, it has turned red. I thought it would, per following click, run the for loop, starting with 5 again, but that it would then return False, and go back to the next index, 4, checking that one, and so forth. I have looked up a lot and I am just stuck. I can't figure it out.
我知道代码从长远来看并不完整;我只是想了解这一步,但是代码可能很丑,所以我可以继续讲下去.
I know that the code is not complete for the long run of the game; I'm just trying to understand this step, however ugly the code might be, so that I can move on to another piece.
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
类名称遍历所有元素,请尝试在click函数中使用jQuery $(this)
关键字.像这样:
Instead of looping through all your elements with .G
class name every time they are clicked, try using the jQuery $(this)
keyword inside your click function. Like this:
function addClickListener(someClass){
$(someClass).each(function () {
this.addEventListener('click', function() {
// an example of how you use the $(this)
$(this).addClass('background-color-red');
});
});
}
这样,您将摆脱for循环和索引问题.
This way, you will get rid of that for loop and your problem with their index.
这篇关于使用JavaScript/jQuery陷入索引5的For循环迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!