0

I have a problem with 'this'. I try to do a simple tic tac toe game and it seems that 'this' in arrChange function is undefined. I have a table with td and th and each of them has a number associated with an ID. The targetID in the end should show me a number (for example "1" if clicked to the top left square of the table (there are 9 squares). How do I pass the value of this from startHere to arrChange? I tried using bind but since I am new to js it did not really work.

var str = '123456789';
var arr = str.split("");


var arrChange = () => {

  var targetID =$(this).attr('id');
  var whereinArr = arr.indexOf(targetID);
  var removeFromArr = arr.splice(whereinArr, 1);
  console.log(targetID);

}

var startHere = ()=> {
  $( "td,th" ).click(function() {
   $(this).css('background', 'blue');
 
    arrChange();

  });
}
startHere();
pau
  • 88
  • 6
  • What do you want to pass to the arrChange function concretely ? – Lyes Jun 30 '20 at 23:55
  • the value of 'this' is undefined. if I put the whole code to the startHere function it works well. So I am not sure why it doesn't work as intended. – pau Jun 30 '20 at 23:59
  • Can you try to wrap it in a variable `var element = $(this)` and pass the variable throught the function ? – Lyes Jul 01 '20 at 00:09
  • thanks for your suggestion, I did try that but it still doesn't work :( – pau Jul 01 '20 at 00:13

0 Answers0