javascript - InnerHTML 未在 JavaScript 中更新

标签 javascript html

当我按下按钮时,我的 insideHTML 没有更新显示,这是一个问题。我正在使用 console.log,我可以看到这些值实际上是第一次更新,但页面没有更新。在下图中,我点击了开始按钮一次,然后点击了两次,您可以看到日志中的值发生变化。这种效果在两个按钮上都会发生,它将更新一次值,然后在后续单击时不会再次更新。而且,网页根本不更新。该程序的目标是制作一个游戏,让计算机在一定范围内猜测你正在思考的数字,你可以选择更高、更低或正确。我是新来的,所以如果将来有什么方法可以改进我的帖子,请告诉我。

Image of webpage with log open

代码如下:

var guess = 0; // Number of guesses remaining
var currentGuess = 0;

function runGame() {

  //get variables from the input fields in HTML form and convert to integer
  var low = parseInt(document.getElementById('lowNum').value);
  var high = parseInt(document.getElementById('highNum').value);
  
  //boolean that checks if the game is won
  if ( document.getElementById('compGuess').value !== ''  ) {
      guess = parseInt(document.getElementById('compGuess').value);
  } else {
      alert ("You have to let the computer have at least one guess!" );
  }
   
  //input validation
  if(low < high && low > 0 && high <= 50 && guess > 0 && guess <= 10) {
      // Input validated
      //alert("Low number: " + low + "\nHigh Number: " + high + "\nComputer Guesses: " + guess);
     
      currentGuess = getRndInteger(low, high); 
      setElementValues();      
      showButtons();
  } else  {
      alert("Invalid selection. Make sure that the number range is between 1 and 50 and guesses are higher than zero.");
  }
    
}

function processGuess( status, currentGuess ) {
    if ( status == 'high' ) {
        currentGuess = currentGuess - 1;
    } else if ( status == 'low' ) {
         currentGuess = currentGuess + 1;
    } else if ( status == 'correct' ) {
        wonGame();
    }
//troubleshooting code
console.log( status ) ;
console.log( currentGuess );
setElementValues();
    return;
}

function setElementValues() {
  
  
  console.log( 'setting values' );
  document.getElementById("computerGuessVal").innerHTML = currentGuess; 
  document.getElementById("guessesLeft").innerHTML = guess;

}

//generate computer guess
function getRndInteger(low, high) {
    
    high = Math.floor(high);
    low = Math.ceil(low);
    return Math.floor(Math.random() * (high - low + 1) ) + low;
}
 
//make bottom buttons visibile
function showButtons() {
  
  document.getElementById("higher").style.visibility = 'visible';
  document.getElementById("lower").style.visibility = 'visible';
  document.getElementById("correct").style.visibility = 'visible';
}
//hide bottom buttons
function hideButtons () {
  
  document.getElementById("higher").style.visibility = 'none';
  document.getElementById("lower").style.visibility = 'none';
  document.getElementById("correct").style.visibility = 'none';     

}

function wonGame () {

 /* document.getElementById("lowNum").innerHTML = 1;
  document.getElementById("highNum").innerHTML = 1;
  document.getElementById("guess").innerHTML = 1;
  document.getElementById("computerGuessVal").innerHTML =" ";       
  document.getElementById("guessesLeft").innerHTML = " ";
  alert("Looks like the computer guessed correctly. Thanks for playing!");
  */
    
  alert("Function yo");
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="generator" content="PSPad editor, www.pspad.com">
  <title>ITEC345-101 Assignment 1</title>
   <script language="JavaScript" src="ITEC345_101_FERGUSON_LAB1.js"></script>
  </head>
  <body>
     <h1>Welcome to the number guessing game. Select a range of numbers between 1 and 50 and the
     computer will try to guess it.<br> Tell the computer how many guesses it gets and see if you can stump it!</h1><br>
    <h2>Pick a number range between 1 and 50</h2>
        Low Number: <input type="number" value = "1" name="lowNum" id="lowNum" ><br>
        High Number: <input type="number" value= "1" name="highNum" id="highNum"><br>
        <br>
        <br>
        <h2>Now think of a number inside that range</h2>
        Number of guesses computer gets (Max 10):<input type="number" value = "1" name="compGuess" id="compGuess">
        <br>
        <br>
        <input type="button" value="Start" onclick="runGame()">
        <br>
        <br>
        <br>
        <font size="12">Current Computer Guess:</font> <h1 id="computerGuessVal"> </h1> <font size="10">Guesses left:</font><h1 id="guessesLeft"></h1>
        <br>
        <br>
        <input type="button" value="Higher" id="higher" style= "visibility:hidden"    onclick="processGuess('high', currentGuess)">  
        <input type="button" value="Lower" id="lower" style= "visibility:hidden"      onclick="processGuess('low', currentGuess)"> 
        <input type="button" value="Correct" id="correct" style= "visibility:hidden"  onclick="processGuess('correct', currentGuess)">
        
  
  </body>
</html>

最佳答案

processGuess() 函数中的变量 currentGuess 是该函数的本地变量,因为函数参数始终是本地变量。因此,当它更新此变量时,不会影响 setElementValues() 放入 .innerHTML 中的全局变量。

无论是通过参数还是使用全局变量传递信息,您都需要保持一致。如果您将当前的猜测作为参数传递,它应该返回更新后的值,并且调用者可以分配全局变量,例如

onclick="currentGuess = processGuess('high', currentGuess);"

或者您可以坚持使用全局变量,这样您就不需要将其作为参数传递。那么它就只是:

onclick="processGuess('high')"

这是使用后一种方法的代码。

var guess = 0; // Number of guesses remaining
var currentGuess = 0;

function runGame() {

  //get variables from the input fields in HTML form and convert to integer
  var low = parseInt(document.getElementById('lowNum').value);
  var high = parseInt(document.getElementById('highNum').value);
  
  //boolean that checks if the game is won
  if ( document.getElementById('compGuess').value !== ''  ) {
      guess = parseInt(document.getElementById('compGuess').value);
  } else {
      alert ("You have to let the computer have at least one guess!" );
  }
   
  //input validation
  if(low < high && low > 0 && high <= 50 && guess > 0 && guess <= 10) {
      // Input validated
      //alert("Low number: " + low + "\nHigh Number: " + high + "\nComputer Guesses: " + guess);
     
      currentGuess = getRndInteger(low, high); 
      setElementValues();      
      showButtons();
  } else  {
      alert("Invalid selection. Make sure that the number range is between 1 and 50 and guesses are higher than zero.");
  }
    
}

function processGuess( status ) {
    if ( status == 'high' ) {
        currentGuess = currentGuess - 1;
    } else if ( status == 'low' ) {
         currentGuess = currentGuess + 1;
    } else if ( status == 'correct' ) {
        wonGame();
    }
//troubleshooting code
console.log( status ) ;
console.log( currentGuess );
setElementValues();
    return;
}

function setElementValues() {
  
  
  console.log( 'setting values' );
  document.getElementById("computerGuessVal").innerHTML = currentGuess; 
  document.getElementById("guessesLeft").innerHTML = guess;

}

//generate computer guess
function getRndInteger(low, high) {
    
    high = Math.floor(high);
    low = Math.ceil(low);
    return Math.floor(Math.random() * (high - low + 1) ) + low;
}
 
//make bottom buttons visibile
function showButtons() {
  
  document.getElementById("higher").style.visibility = 'visible';
  document.getElementById("lower").style.visibility = 'visible';
  document.getElementById("correct").style.visibility = 'visible';
}
//hide bottom buttons
function hideButtons () {
  
  document.getElementById("higher").style.visibility = 'none';
  document.getElementById("lower").style.visibility = 'none';
  document.getElementById("correct").style.visibility = 'none';     

}

function wonGame () {

 /* document.getElementById("lowNum").innerHTML = 1;
  document.getElementById("highNum").innerHTML = 1;
  document.getElementById("guess").innerHTML = 1;
  document.getElementById("computerGuessVal").innerHTML =" ";       
  document.getElementById("guessesLeft").innerHTML = " ";
  alert("Looks like the computer guessed correctly. Thanks for playing!");
  */
    
  alert("Function yo");
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="generator" content="PSPad editor, www.pspad.com">
  <title>ITEC345-101 Assignment 1</title>
   <script language="JavaScript" src="ITEC345_101_FERGUSON_LAB1.js"></script>
  </head>
  <body>
     <h1>Welcome to the number guessing game. Select a range of numbers between 1 and 50 and the
     computer will try to guess it.<br> Tell the computer how many guesses it gets and see if you can stump it!</h1><br>
    <h2>Pick a number range between 1 and 50</h2>
        Low Number: <input type="number" value = "1" name="lowNum" id="lowNum" ><br>
        High Number: <input type="number" value= "1" name="highNum" id="highNum"><br>
        <br>
        <br>
        <h2>Now think of a number inside that range</h2>
        Number of guesses computer gets (Max 10):<input type="number" value = "1" name="compGuess" id="compGuess">
        <br>
        <br>
        <input type="button" value="Start" onclick="runGame()">
        <br>
        <br>
        <br>
        <font size="12">Current Computer Guess:</font> <h1 id="computerGuessVal"> </h1> <font size="10">Guesses left:</font><h1 id="guessesLeft"></h1>
        <br>
        <br>
        <input type="button" value="Higher" id="higher" style= "visibility:hidden"    onclick="processGuess('high')">  
        <input type="button" value="Lower" id="lower" style= "visibility:hidden"      onclick="processGuess('low')"> 
        <input type="button" value="Correct" id="correct" style= "visibility:hidden"  onclick="processGuess('correct')">
        
  
  </body>
</html>

关于javascript - InnerHTML 未在 JavaScript 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42125150/

相关文章:

javascript - 如何将Firebase上传图像的图像downloadURL转换为base64

javascript - 如何将 DOM 元素保存/导出到图像?

html - 如何使用 Handlebars 遍历 JSON 结构

javascript - 如何绑定(bind)到 AngularJS 中的表单属性?

javascript - 如何在 Javascript 中查找复杂对象数组中的最小值/最大值?

php - 使用 PHP、Xpath 和/或 DOM 更改 HTML 内容

javascript - Bootstrap 网格元素重叠导航栏

html - 如何让 Firefox 在文件更改时自动刷新?

javascript - 在潜在客户资格后创建机会时,设置机会查找值不起作用

javascript - 是否可以使用 AngularJS $formatters 添加额外的零? (或者以任何可能的方式,输入数字?)