admin管理员组

文章数量:1023738

Trying to make simple tic-tac-toe game. I'm trying to change the button's value when clicked, but I don't know which one the user will click first. Obviously, I've got 9 buttons like this:

<input type="button" id="Button1" onclick="Button1_Click()" />

and a function like this, to handle their onclick event.

<script>
    var Caption = "X";
    function Button1_Click() {
        document.getElementById('Button1').value = Caption;
        if (Caption=="X") {
            Caption = "O";
            Caption="X";
        }
    }
</script>

But the thing is, when i click other buttons, The caption is always the same (X), how can I change it?

Trying to make simple tic-tac-toe game. I'm trying to change the button's value when clicked, but I don't know which one the user will click first. Obviously, I've got 9 buttons like this:

<input type="button" id="Button1" onclick="Button1_Click()" />

and a function like this, to handle their onclick event.

<script>
    var Caption = "X";
    function Button1_Click() {
        document.getElementById('Button1').value = Caption;
        if (Caption=="X") {
            Caption = "O";
            Caption="X";
        }
    }
</script>

But the thing is, when i click other buttons, The caption is always the same (X), how can I change it?

Share Improve this question edited Aug 26, 2021 at 6:24 Miss.Alpha asked May 21, 2016 at 8:11 Miss.AlphaMiss.Alpha 1541 gold badge2 silver badges11 bronze badges 4
  • you are setting Caption first and then you evaluate the value, you already assigned. please post some more of your code, because you might have more errors than that. just a small hint, please use variables with starting small letters. caps starting is usualy a sign of a class. – Nina Scholz Commented May 21, 2016 at 8:14
  • you set always Caption = "X" (last row), you have to remove this line :) also move "document.getElementById..." at the end (after the if statement) – Cyril Iselin Commented May 21, 2016 at 8:14
  • 1 How do you attach onclick event? – dfsq Commented May 21, 2016 at 8:15
  • It seems you need to first get the value of the clicked button, and assign it to a variable. And then do an if else, if button value is X then set it to 0, else if button value if 0 then set it to X... – Bengi Besceli Commented May 21, 2016 at 8:34
Add a ment  | 

5 Answers 5

Reset to default 2

Method 1: Closure

One way to do it is using a closure for the click handler, so it knows which button was pressed. Keep track of who'se turn it is in a variable.

// Do this only when the page is loaded.
window.addEventListener('DOMContentLoaded', function() {

  // Variable to keep track of turns in.
  var Xturn = true;

  // A function that returns a specific click handler for a button.
  function createClickHandler(element, index) {
    
    // The anonymous function that is returned is the actual click handler.
    return function() {
      
      // Logs text in the console (press F12 to view it). Very useful for testing/debugging!
      console.log('Button ' + index + ' clicked');
      
      // Only do something if this button was still open.
      if (element.innerText == '') {
        element.innerText = Xturn ? 'X' : 'O';
        Xturn = !Xturn; // Toggle player
      };
      
    }
    
  }

  // Now for the actual initialisation:
  // Find all buttons.
  var buttons = document.querySelectorAll('button');

  // Attach a click handler to each of them.
  for (n = 0; n < buttons.length; n++) {
    buttons.item(n).addEventListener('click', createClickHandler(buttons.item(n), n));
  }

});
button {
  width: 50px;
  height: 50px;
  line-height: 50px;
  vertical-align: bottom;
}
<div>
  <button/><button/><button/>
</div>
<div>
  <button/><button/><button/>
</div>
<div>
  <button/><button/><button/>
</div>

Method 2: Event target

When an event is triggered, the event handler gets an event object as a parameter. This object contains information about the event, like the element that triggered it. This way you can also find the button. If you give every button an id or other recognizable property, you can distinguish between the buttons.

You can bind an event handler on every button, but it's even easier to bind it to a parent element. You can even bind the click handler to the document. That way you also don't have to wait for the DOM to be loaded. The even handler will capture every click, and it will even capture clicks on elements that are dynamically added later.

Inside the event handler, you can get the element that triggered it, and only respond if it is one of the buttons of the game:

// Variable to keep track of turns in.
var Xturn = true;


document.addEventListener('click', function(event) {
  var event = event || window.event;
  var element = event.target || event.srcElement;

  // Only respond to button clicks
  if (element.tagName == 'BUTTON') {

    console.log('Button ' + element.id + ' clicked');
    
    // Only do something if this button was still open.
    if (element.innerText == '') {
      element.innerText = Xturn ? 'X' : 'O';
      Xturn = !Xturn; // Toggle player
    }
  }

});
button {
  width: 50px;
  height: 50px;
  line-height: 50px;
  vertical-align: bottom;
}
<div>
  <button id='b1' /><button id='b2' /><button id='b3' />
</div>
<div>
  <button id='b4' /><button id='b5' /><button id='b6' />
</div>
<div>
  <button id='b7' /><button id='b8' /><button id='b9' />
</div>

I think you may just change your Button1_Click() like below:

function Button1_Click() {
    document.getElementById('Button1').value = Caption;
    if (Caption=="X") {
        Caption = "O";
    } else {
        Caption="X";
    }
}

But, in this way, you said you have 9 buttons. Then you have to create 9 separated but look quite the same function like the one above. How about this:

<!--You need to make it look better..-->
<div id='buttonParent'>
  <input type='button' id='btn1'>
  <input type='button' id='btn2'>
  <input type='button' id='btn3'>
  <input type='button' id='btn4'>
  <input type='button' id='btn5'>
  <input type='button' id='btn6'>
  <input type='button' id='btn7'>
  <input type='button' id='btn8'>
  <input type='button' id='btn9'>
</div>

<script>
// wrap all your 9 buttons in a tag <div id='buttonParent'> or whatever you like.
var buttonParentNode = document.getElementById('buttonParent');
var button_click = function(e) {
  // this function handle all button click event
  var btn = e.target; // DOM element which was click. It must be any tag inside buttonParentNode
  if (btn.tagName == 'INPUT') { // if DOM element is a input tag. 
    if (btn.innerHTML == 'X') {
      btn.innerHTML = 'O';
    } else {
      btn.innerHTML = 'X';
    }
  }
};

buttonParentNode.addEventListener('click', button_click, false);
</script>

function button_Click(e) {
  if(e.value === 'X') {
    e.value = 'O';
  } else {
    e.value = 'X';
  }
}
<input type="button" id="button1" onclick="button_Click(this)" value="X" />
<input type="button"  id="button2" onclick="button_Click(this)" value="O" />
<input type="button"  id="button3" onclick="button_Click(this)" value="X" />
<input type="button"  id="button4" onclick="button_Click(this)" value="O" />
<input type="button"  id="button5" onclick="button_Click(this)" value="X" />
<input type="button"  id="button6" onclick="button_Click(this)" value="O" />
<input type="button"  id="button7" onclick="button_Click(this)" value="X" />
<input type="button"  id="button8" onclick="button_Click(this)" value="O" />
<input type="button"  id="button9" onclick="button_Click(this)" value="X" />
<input type="button"  id="button10" onclick="button_Click(this)" value="O" />

However a better approach would be as follows:

document.addEventListener("DOMContentLoaded", buttonClickHandler);

function buttonClickHandler() {
  var buttons = document.getElementsByClassName('button');
  
  for(var i = 0; i < buttons.length; i++) {
     buttons[i].addEventListener('click', function() {
       if(this.value === 'X') {
         this.value = 'O';
       } else {
         this.value = 'X';
       }
     });
  }
}
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />

try this,

<html>
<head>
    <script src="https://ajax.googleapis./ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>

<body>
    <div>
        <input type="button" id="Button1" class="btn" onclick="Button1_Click(this)" />
        <input type="button" id="Button2" class="btn" onclick="Button1_Click(this)" />
        <input type="button" id="Button3" class="btn" onclick="Button1_Click(this)" />
    </div>

    <div>
        <input type="button" id="Button4" class="btn" onclick="Button1_Click(this)" />
        <input type="button" id="Button5" class="btn" onclick="Button1_Click(this)" />
        <input type="button" id="Button6" class="btn" onclick="Button1_Click(this)" />
    </div>
    <div>
        <input type="button" id="Button7" class="btn" onclick="Button1_Click(this)" />
        <input type="button" id="Button8" class="btn" onclick="Button1_Click(this)" />
        <input type="button" id="Button9" class="btn" onclick="Button1_Click(this)" />
    </div>
    <script>
        var Caption = "X";
        function Button1_Click(btn) {

            $(btn).val(Caption);

            if (Caption == "X") {
                Caption = "O";
            } else {
                Caption = "X";
            }
        }
    </script>
</body>
</html>
<input type="button" value='  ' onclick="Button_Click(this)" />
<input type="button" value='  ' onclick="Button_Click(this)" />
<input type="button" value='  ' onclick="Button_Click(this)" /> <br/>
<input type="button" value='  ' onclick="Button_Click(this)" />
<input type="button" value='  ' onclick="Button_Click(this)" />
<input type="button" value='  ' onclick="Button_Click(this)" /> <br/>
<input type="button" value='  ' onclick="Button_Click(this)" />
<input type="button" value='  ' onclick="Button_Click(this)" />
<input type="button" value='  ' onclick="Button_Click(this)" /> <br/>

<script>
var turn = 'x';
function Button_Click(btn) {
    if (btn.value == '  ') {
        btn.value = turn;
        turn = (turn == 'x') ? 'o' : 'x';
    }
}
</script>

You may try it here

Trying to make simple tic-tac-toe game. I'm trying to change the button's value when clicked, but I don't know which one the user will click first. Obviously, I've got 9 buttons like this:

<input type="button" id="Button1" onclick="Button1_Click()" />

and a function like this, to handle their onclick event.

<script>
    var Caption = "X";
    function Button1_Click() {
        document.getElementById('Button1').value = Caption;
        if (Caption=="X") {
            Caption = "O";
            Caption="X";
        }
    }
</script>

But the thing is, when i click other buttons, The caption is always the same (X), how can I change it?

Trying to make simple tic-tac-toe game. I'm trying to change the button's value when clicked, but I don't know which one the user will click first. Obviously, I've got 9 buttons like this:

<input type="button" id="Button1" onclick="Button1_Click()" />

and a function like this, to handle their onclick event.

<script>
    var Caption = "X";
    function Button1_Click() {
        document.getElementById('Button1').value = Caption;
        if (Caption=="X") {
            Caption = "O";
            Caption="X";
        }
    }
</script>

But the thing is, when i click other buttons, The caption is always the same (X), how can I change it?

Share Improve this question edited Aug 26, 2021 at 6:24 Miss.Alpha asked May 21, 2016 at 8:11 Miss.AlphaMiss.Alpha 1541 gold badge2 silver badges11 bronze badges 4
  • you are setting Caption first and then you evaluate the value, you already assigned. please post some more of your code, because you might have more errors than that. just a small hint, please use variables with starting small letters. caps starting is usualy a sign of a class. – Nina Scholz Commented May 21, 2016 at 8:14
  • you set always Caption = "X" (last row), you have to remove this line :) also move "document.getElementById..." at the end (after the if statement) – Cyril Iselin Commented May 21, 2016 at 8:14
  • 1 How do you attach onclick event? – dfsq Commented May 21, 2016 at 8:15
  • It seems you need to first get the value of the clicked button, and assign it to a variable. And then do an if else, if button value is X then set it to 0, else if button value if 0 then set it to X... – Bengi Besceli Commented May 21, 2016 at 8:34
Add a ment  | 

5 Answers 5

Reset to default 2

Method 1: Closure

One way to do it is using a closure for the click handler, so it knows which button was pressed. Keep track of who'se turn it is in a variable.

// Do this only when the page is loaded.
window.addEventListener('DOMContentLoaded', function() {

  // Variable to keep track of turns in.
  var Xturn = true;

  // A function that returns a specific click handler for a button.
  function createClickHandler(element, index) {
    
    // The anonymous function that is returned is the actual click handler.
    return function() {
      
      // Logs text in the console (press F12 to view it). Very useful for testing/debugging!
      console.log('Button ' + index + ' clicked');
      
      // Only do something if this button was still open.
      if (element.innerText == '') {
        element.innerText = Xturn ? 'X' : 'O';
        Xturn = !Xturn; // Toggle player
      };
      
    }
    
  }

  // Now for the actual initialisation:
  // Find all buttons.
  var buttons = document.querySelectorAll('button');

  // Attach a click handler to each of them.
  for (n = 0; n < buttons.length; n++) {
    buttons.item(n).addEventListener('click', createClickHandler(buttons.item(n), n));
  }

});
button {
  width: 50px;
  height: 50px;
  line-height: 50px;
  vertical-align: bottom;
}
<div>
  <button/><button/><button/>
</div>
<div>
  <button/><button/><button/>
</div>
<div>
  <button/><button/><button/>
</div>

Method 2: Event target

When an event is triggered, the event handler gets an event object as a parameter. This object contains information about the event, like the element that triggered it. This way you can also find the button. If you give every button an id or other recognizable property, you can distinguish between the buttons.

You can bind an event handler on every button, but it's even easier to bind it to a parent element. You can even bind the click handler to the document. That way you also don't have to wait for the DOM to be loaded. The even handler will capture every click, and it will even capture clicks on elements that are dynamically added later.

Inside the event handler, you can get the element that triggered it, and only respond if it is one of the buttons of the game:

// Variable to keep track of turns in.
var Xturn = true;


document.addEventListener('click', function(event) {
  var event = event || window.event;
  var element = event.target || event.srcElement;

  // Only respond to button clicks
  if (element.tagName == 'BUTTON') {

    console.log('Button ' + element.id + ' clicked');
    
    // Only do something if this button was still open.
    if (element.innerText == '') {
      element.innerText = Xturn ? 'X' : 'O';
      Xturn = !Xturn; // Toggle player
    }
  }

});
button {
  width: 50px;
  height: 50px;
  line-height: 50px;
  vertical-align: bottom;
}
<div>
  <button id='b1' /><button id='b2' /><button id='b3' />
</div>
<div>
  <button id='b4' /><button id='b5' /><button id='b6' />
</div>
<div>
  <button id='b7' /><button id='b8' /><button id='b9' />
</div>

I think you may just change your Button1_Click() like below:

function Button1_Click() {
    document.getElementById('Button1').value = Caption;
    if (Caption=="X") {
        Caption = "O";
    } else {
        Caption="X";
    }
}

But, in this way, you said you have 9 buttons. Then you have to create 9 separated but look quite the same function like the one above. How about this:

<!--You need to make it look better..-->
<div id='buttonParent'>
  <input type='button' id='btn1'>
  <input type='button' id='btn2'>
  <input type='button' id='btn3'>
  <input type='button' id='btn4'>
  <input type='button' id='btn5'>
  <input type='button' id='btn6'>
  <input type='button' id='btn7'>
  <input type='button' id='btn8'>
  <input type='button' id='btn9'>
</div>

<script>
// wrap all your 9 buttons in a tag <div id='buttonParent'> or whatever you like.
var buttonParentNode = document.getElementById('buttonParent');
var button_click = function(e) {
  // this function handle all button click event
  var btn = e.target; // DOM element which was click. It must be any tag inside buttonParentNode
  if (btn.tagName == 'INPUT') { // if DOM element is a input tag. 
    if (btn.innerHTML == 'X') {
      btn.innerHTML = 'O';
    } else {
      btn.innerHTML = 'X';
    }
  }
};

buttonParentNode.addEventListener('click', button_click, false);
</script>

function button_Click(e) {
  if(e.value === 'X') {
    e.value = 'O';
  } else {
    e.value = 'X';
  }
}
<input type="button" id="button1" onclick="button_Click(this)" value="X" />
<input type="button"  id="button2" onclick="button_Click(this)" value="O" />
<input type="button"  id="button3" onclick="button_Click(this)" value="X" />
<input type="button"  id="button4" onclick="button_Click(this)" value="O" />
<input type="button"  id="button5" onclick="button_Click(this)" value="X" />
<input type="button"  id="button6" onclick="button_Click(this)" value="O" />
<input type="button"  id="button7" onclick="button_Click(this)" value="X" />
<input type="button"  id="button8" onclick="button_Click(this)" value="O" />
<input type="button"  id="button9" onclick="button_Click(this)" value="X" />
<input type="button"  id="button10" onclick="button_Click(this)" value="O" />

However a better approach would be as follows:

document.addEventListener("DOMContentLoaded", buttonClickHandler);

function buttonClickHandler() {
  var buttons = document.getElementsByClassName('button');
  
  for(var i = 0; i < buttons.length; i++) {
     buttons[i].addEventListener('click', function() {
       if(this.value === 'X') {
         this.value = 'O';
       } else {
         this.value = 'X';
       }
     });
  }
}
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />

try this,

<html>
<head>
    <script src="https://ajax.googleapis./ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>

<body>
    <div>
        <input type="button" id="Button1" class="btn" onclick="Button1_Click(this)" />
        <input type="button" id="Button2" class="btn" onclick="Button1_Click(this)" />
        <input type="button" id="Button3" class="btn" onclick="Button1_Click(this)" />
    </div>

    <div>
        <input type="button" id="Button4" class="btn" onclick="Button1_Click(this)" />
        <input type="button" id="Button5" class="btn" onclick="Button1_Click(this)" />
        <input type="button" id="Button6" class="btn" onclick="Button1_Click(this)" />
    </div>
    <div>
        <input type="button" id="Button7" class="btn" onclick="Button1_Click(this)" />
        <input type="button" id="Button8" class="btn" onclick="Button1_Click(this)" />
        <input type="button" id="Button9" class="btn" onclick="Button1_Click(this)" />
    </div>
    <script>
        var Caption = "X";
        function Button1_Click(btn) {

            $(btn).val(Caption);

            if (Caption == "X") {
                Caption = "O";
            } else {
                Caption = "X";
            }
        }
    </script>
</body>
</html>
<input type="button" value='  ' onclick="Button_Click(this)" />
<input type="button" value='  ' onclick="Button_Click(this)" />
<input type="button" value='  ' onclick="Button_Click(this)" /> <br/>
<input type="button" value='  ' onclick="Button_Click(this)" />
<input type="button" value='  ' onclick="Button_Click(this)" />
<input type="button" value='  ' onclick="Button_Click(this)" /> <br/>
<input type="button" value='  ' onclick="Button_Click(this)" />
<input type="button" value='  ' onclick="Button_Click(this)" />
<input type="button" value='  ' onclick="Button_Click(this)" /> <br/>

<script>
var turn = 'x';
function Button_Click(btn) {
    if (btn.value == '  ') {
        btn.value = turn;
        turn = (turn == 'x') ? 'o' : 'x';
    }
}
</script>

You may try it here

本文标签: javascriptChange a variable when button is clickedStack Overflow