简体   繁体   English

单击按钮时更改变量

[英]Change a variable when button is clicked

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: 显然,我有9个这样的按钮:

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

and a function like this, to handle their onclick event. 以及类似的函数来处理其onclick事件。

<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? 但是问题是,当我单击其他按钮时,标题始终是相同的(X),如何更改它?

Method 1: Closure 方法1:关闭

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 方法2:事件目标

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. 如果为每个按钮提供id或其他可识别的属性,则可以区分按钮。

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. 这样,您也不必等待DOM加载。 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: 我认为您可以像下面那样更改Button1_Click()

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. 但是,这样,您说您有9个按钮。 Then you have to create 9 separated but look quite the same function like the one above. 然后,您必须创建9个分隔的控件,但看起来与上面的功能完全相同。 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.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>
<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 你可以在这里尝试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM