JavaScript 中的 textContent 未显示正确的输出

textContent in JavaScript not showing the correct output

On the left is the results from textContent

图片中的一些上下文。我试图通过在每次用户单击按钮时将 textContent 调用到 window 来操纵 DOM,同时还将其记录在终端中。但是,假设如果我点击剪刀然后快速点击摇滚按钮,即使我可以从终端看到按钮确实被点击并登录到终端,点击摇滚按钮产生的 textContent 也不会被调用我每次都需要等待 ~1s,以便 textContent 可以打印为正确的语句。有没有一种方法可以让我单击按钮,textContent 将精确地打印出所需的语句?

const container = document.querySelector(".container")

const content = document.createElement('div')
content.classList.add('result')
container.appendChild(content)


const buttons = document.querySelectorAll('button')
buttons.forEach(button => button.addEventListener('click', playGame));

function computerPlay() {
  let responses = ["rock", "paper", "scissor"];
  response = responses[Math.floor(Math.random() * responses.length)];
  return response;
  // console.log(response)
}

function playGame(e) {
  let userScore = 0
  let computerScore = 0
  playerResponse = e.target.className;
  computerSelection = computerPlay()  
  console.log(playerResponse)
  // console.log(computerSelection)
  // for (let i = userScore; i < 5; i++){
    if (playerResponse == 'scissor' && computerSelection == 'paper') {
      // console.log("It's a tie!")
      content.textContent = "You win! Scissor beats paper"
    } else if (playerResponse == "paper" && computerSelection == "rock") {
      userScore++
      // console.log("You win, scissor beats paper")
      content.textContent = "You win! Paper beats rock"
    } else if (playerResponse == "rock" && computerSelection == "scissor") {
      userScore++
      // console.log("You win, rock beats scissor")
      content.textContent = "You win! Rock beats scissor"
    } else if (playerResponse === computerSelection) {
      // console.log("You win, paper beats rock")
      content.textContent = `You both choose ${playerResponse}, it's a tie!`
    } else {
      computerScore++
      // console.log("You lose, try again!")
      content.texContent = "You lose, try again!!"
    }
    
  // }
  // console.log(computerScore)
  // console.log(userScore)
}

我对JS还是新手所以代码真的很乱

问题是你只为 content.textContent 分配了一个新的字符串值,但你没有在它之后立即更新 DOM 节点。

将以下代码选项放在 playgame() 函数的底部

添加另一条消息: 如果您想添加另一条消息,您必须再次执行 container.appendChild(content)。

正在更新消息: 例如,您可以通过编辑当前 DOM 节点的 innerHTML 轻松更新屏幕上的文本。

document.querySelector(".result").innerHTML = content.textContent;