如何使if语句对HTML元素的内容作出反应?

  • 本文关键字:if 何使 语句 元素 HTML javascript
  • 更新时间 :
  • 英文 :


我正在尝试制作一款tik tak toe游戏,当有人赢得游戏时,我正在努力制作警报。这是我到目前为止所做的一个JSFiddle,不包括任何关于有人获胜时的警报的内容。

我的计划是为每一种可能获胜的方式(只有8种)创建if语句。我想通过创建以下类型的代码来实现这一点,但我不知道怎么做。

这不是真正的代码,但它是我想要完成的英文版本。

if(HTML element id="topLeft" displays "X" && HTML element id="topCenter" displays "X" && HTML element id="topRight" displays "X"){
alert(Player X has won);
}

我试着用这个代码完成这个(这是我在写实际的javascript代码的尝试)

if(document.getElementById("bottomRight").innerHTML=="X"){
alert("X");
}

我可以看出为什么这是不正确的,但不是真的。我知道我想要完成什么,但我不知道如何在javascript语言中做到这一点。我试图使一个if语句当一个html元素显示一个特定的文本。在tik tak toe的情况下,它要么是"X"或";O"。我不确定这是否可能,但我想是可能的。我知道可能有一种更有效的方法来做到这一点,但是,我对编码相当陌生。我愿意听取不同的解决方案,但请记住,如果它们过于复杂,我将无法理解它们。谢谢你的阅读,谢谢你的帮助。

从您的问题的上下文中,我了解到您正在试图观察HTML中的变化。如果这是正确的,那么JavaScript为您的挣扎提供了一个很好的解决方案。MutationObserver API。

const targetNode = document.getElementById('game-board');
// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
// Use traditional 'for loops' for IE 11
for(const mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('A child node has been added or removed.');
}
else if (mutation.type === 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// Later, you can stop observing
observer.disconnect();

来源:https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

虽然,我建议你考虑一个不同的解决方案,使用数组和创建事件驱动的应用程序,其中每次点击有相同的回调函数,并检查数组中的元素是否应该被改变。一旦你做到了这一点,你就可以在同一个回调函数中创建一个条件,如果玩家的移动是获胜的。

我已经添加了一些指针,评估函数。不确定这是否是你想要的,或者对你来说足够简单。但是看看

//New helper function
function evaluate() {
if(document.getElementById("bottomRight").innerHTML=="X"){
alert("X");
}
}

let topLeftClicked=false;
// YOUR ORIGINAL CODE ....
function bottomRight(){
if(!bottomRightClicked){
bottomRightClicked=true;
document.getElementById("bottomRight").innerHTML=
XorO;
XtoO();
}
// Calling evaluate
evaluate();
}

这是您的小提琴修改和增强的代码版本。handleSquareClick函数是主要的监听器,但getWinnerIfAnygetTextIfThreeMatch处理了许多您正在努力解决的win-assessment逻辑。

通读代码内注释,详细了解脚本的功能。

//
// Identifies some DOM elements
//
const board = document.getElementsByClassName("board")[0];
const squares = document.getElementsByClassName("square");

//
// Sets up the 8 "winning" groups of 3 squares each (row, columns, and diagonals) 
//
// Hard codes group names to match the HTML class names -- (It would be smarter to make 
//   ONE canonical set of names, then DERIVE the other set of names, but I was lazy.)
const groupNames = ["top","middle","bottom","left","center","right","downDiag","upDiag"];
// Binds an arrow function to the name `makeGroup`. The function will take a group name
//   and return an array containing the 3 DOM squares that have a corresponding class name
const makeGroup = (groupName) => 
Array.from(squares).filter(square => square.classList.contains(groupName));
// Defines an array of arrays: the 8 "winning" groups of squares (one for each group name)
const groups = groupNames.map(groupName => makeGroup(groupName));

//
// Sets up a function that can toggle between X and O
//
// The `makeFunctionToToggleCharacters` function returns a new function,
//   which gets bound to the name `toggleChar` and will always return "X" or "O"
const toggleChar = makeFunctionToToggleCharacters();

//
// An event listener (named handleSquareClick) will respond to user actions
//
//  It directly relies on:
//    isEmptySquare - assesses relavence of click
//    toggleChar        - chooses X or O
//    getStatus         - checks whether game is over
//    handleGameEnd - stops UI and announces winner
//
//  With addtional help from:
//    getWinnerIfAny            - explores winning groups
//    getTextIfThreeMatch - compares squares in a group
//    allSquaresFull            - notices drawn games
//  
// Calls `handleSquareClick` whenever user clicks anything within the board
board.addEventListener("click", handleSquareClick);
// Defines our click listener
function handleSquareClick(event){ // Listeners can access triggering events
const clickee = event.target; // Event has a useful "target" property
if(!isEmptySquare(clickee)){ return; } // Ignores irrelevant clicks
clickee.innerHTML = toggleChar(); // Updates to X or O, and writes it to the DOM
// Calls `getStatus` to check for end of game (win or draw)
const statusText = getStatus();
// Calls `handleGameEnd` if game is over
if(statusText !== "playing"){
handleGameEnd(statusText);
}
// Else, we're still playing, so the page just waits for another click
}
function isEmptySquare(element){
// Returns true if the clicked element is an empty square
return element.classList.contains("square") && element.innerHTML === "";
}
function getStatus(){
// Defines, updates, and returns a statusText string
// (Uses getWinnerIfAny and allSquaresFull to make updates)
let statusText = "playing";
// Calls getWinnerIfAny, and possibly updates statusText
const winner = getWinnerIfAny(Array.from(squares));
if(winner != ""){
statusText = `${winner} wins!`;
}
// Calls allSquaresFull, and possibly updates statusText
else if(allSquaresFull(Array.from(squares)) === true){
statusText = "Drawn game";
}
// Returns the text to the function that called getStatus (the click listener)
return statusText;
}

function getWinnerIfAny(){
// Loops through the "winnable" groups, destructuring each group into 3 separate
//   "member" squares, which are all passed as arguments into `getTextIfThreeMatch`
// If all 3 members of any group contain identical text, returns that text (which
//   will be"X" or "O"), and stops looping
// (If no group's members all contain identical text, returns the empty string)
for ([memberA, memberB, memberC] of groups){ // This uses "array destructutring"
const winner = getTextIfThreeMatch(memberA, memberB, memberC)
if(winner != ""){
return winner; // Breaks out of loop early if a winner is found
}
}
return ""; // Returns empty string by default
}
function getTextIfThreeMatch(squareA, squareB, squareC){
// Given 3 squares, if they have the same (non-empty) textContent, returns that text
// Else, returns the empty string
const
textA = squareA.textContent,
textB = squareB.textContent,
textC = squareC.textContent;
if((textA != "") && (textB === textA) && (textC === textA)){
return textA;
}
else{
return "";
}
}
function handleGameEnd(status){
// Stops responding to clicks, and updates the display
board.removeEventListener("click", handleSquareClick);
board.classList.add("done");
console.log(status);
}
function allSquaresFull(arrayOfSquares){
// Returns true if no legal moves are left
// (Note: this doesn't always mean a draw, b/c X can win on the last move)
return !arrayOfSquares.some(
square => isEmptySquare(square)
);
}

//
// Defines the function that creates the character-toggling function used above
//
function makeFunctionToToggleCharacters(){
let char; // "char" only exists in this context (and starts undefined)
// nextCharFunc is a closure -- it can access this context later
function nextCharFunc(){
if (char === "X"){ char = "O"; }
else{ char = "X"; }  // default output will be "X" (defines char if necessary)
return char;
}
// The returned function will be the only way to access "char" later
return nextCharFunc;
}
.board { display: grid; grid-template-columns: 20px 20px 20px; }
.square { font-size: 1.2em; height: 1.2em; padding: 0; margin: 0; border: 1px solid gray; }
.done .square { background-color: rosybrown; }
<div class="board">
<p class="square top left downDiag"></p>
<p class="square top center"></p>
<p class="square top right upDiag" data-row="top"></p>
<p class="square middle left"></p>
<p class="square middle center downDiag upDiag"></p>
<p class="square middle right"></p>
<p class="square bottom left upDiag"></p>
<p class="square bottom center"></p>
<p class="square bottom right downDiag"></p>
</div>

最新更新