简体   繁体   中英

Getting Text out of HTML into Javascript as a Function with Input Changing IDs

I am trying to create an if/else statement that checks the text of a button that the user presses. If there is no text in that button, it continues the function, if there is pre-existing text then it gives an alert stating that there is already an entry there.

Essentially, the user clicks a button and the code checks to see if that button is empty or not. However, since the button's ID is constantly changing, I don't know how to tell the code to check the pressed button. I feel that using 'this' is part of the solution to this problem, but I am too new to JavaScript to use it correctly.

This is my entire JavaScript code, off it works fine except for the two lines that have comments in them. I am trying to make the variable "inSquare" to equal the text from the button that triggered the function. Then it goes on to check the text of the variable, but currently all it does is fail the if and head straight to the else.

var turnNumber = 9;
var whoseTurn;
var inSquare;
function currentTurn(id) {
    inSquare = this.innerHTML; /*This Line*/
    if (inSquare === "") { /*This Line*/
        if (whoseTurn === 0) {
            id.innerHTML = "X";
            turnNumber -= 1;
            whoseTurn = turnNumber % 2;
        } else {
            id.innerHTML = "O";
            turnNumber -= 1;
            whoseTurn = turnNumber % 2;
        }
    } else {
        window.alert("Something is already in that square!");
    }
}

Also, here is an example of what the HTML buttons look like. (There are nine total, but they are all formatted the same).

<button id="topLeft" onclick="currentTurn(this)"></button>
<button id="topMid" onclick="currentTurn(this)"></button>
<button id="topRight" onclick="currentTurn(this)"></button>

inSquare = this.innerHTML; should be inSquare = id.innerHTML;

this in your function refers to the window object, but you want to refer to the element you passed, which you provided as the id argument of the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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