Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...