Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

Stuck in For loop iteration of index 5 using javascript/jQuery

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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');
      });
  });?
}

This way, you will get rid of that for loop and your problem with their index.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...