单击按钮时更改变量

时间:2016-05-21 08:11:20

标签: javascript html

尝试制作简单的井字游戏。我点击时尝试更改按钮的值,但我不知道用户将首先点击哪一个。显然,我有9个这样的按钮:

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

和这样的函数来处理他们的onclick事件。

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

但问题是,当我点击其他按钮时,标题总是相同的(X),我该如何更改?

5 个答案:

答案 0 :(得分:1)

方法1:关闭

一种方法是使用闭包处理程序的闭包,因此它知道按下了哪个按钮。跟踪谁将其变为变量。

&#13;
&#13;
// 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));
  }

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

方法2:事件目标

触发事件时,事件处理程序将事件对象作为参数获取。此对象包含有关事件的信息,例如触发它的元素。这样你也可以找到按钮。如果你给每个按钮一个id或其他可识别的属性,你可以区分按钮。

您可以在每个按钮上绑定事件处理程序,但它更容易将其绑定到父元素。您甚至可以将单击处理程序绑定到文档。这样你也不必等待加载DOM。偶数处理程序将捕获每次单击,甚至可以捕获稍后动态添加的元素的点击。

在事件处理程序中,您可以获取触发它的元素,只有在它是游戏按钮之一时才会响应:

&#13;
&#13;
// 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
    }
  }

});
&#13;
button {
  width: 50px;
  height: 50px;
  line-height: 50px;
  vertical-align: bottom;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我想您可能只需更改 Button1_Click(),如下所示:

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

但是,通过这种方式,你说你有9个按钮。然后你必须创建9分离,但看起来完全相同的功能,如上面的那个。 怎么样:

<!--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>

答案 2 :(得分:0)

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" />

然而,更好的方法如下:

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" />

答案 3 :(得分:-1)

试试这个,

<html>
<head>
    <script src="https://ajax.googleapis.com/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>

答案 4 :(得分:-2)

<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>

您可以尝试here