简体   繁体   中英

input.value in array return 0

i'm makeing score counter and i'm trying to display a message with the value of my winning score input (Where the player chooses how many points to play).

When I use input.value outside the array, it works fine. But when I try to use it within the array, it returns me 0.

 var input = document.querySelector("#scoresInput"); var msgWindow = document.querySelector("#msgWindow"); var wsDisplay = document.querySelector("p span") // winning score display input.addEventListener("change", function(){ if(this.value <= 0){ msg("errorMsg", 2); }else{ msg("newMsg", 1); wsDisplay.textContent = this.value; } }); var msgIndex = [ "new game begins now you play to " + input.value + " scores", "you can't play to " + input.value + " scores(", "! player 1 is the winner!", "! player 2 is the winner!" ]; function msg(msgClass, i){ msgWindow.classList.add(msgClass); msgWindow.textContent = msgIndex[i]; } 
  <h1><span id="p1Display">0</span> - <span id="p2Display">0</span</h1> <p>you play to <span>3</span></p> <input id="scoresInput" type= "number"> <button id="p1">player1</button> <button id="p2">player2</button> <button id="reset">newGame</button> <p id="msgWindow"></p> 

//I expect the real time output of the input value but input.value in the array always return 0.

Using a variable in an array value copies the value at the time you execute the assignment, it doesn't make it re-evaluate the variable each time the array is used.

You can put a placeholder in the string, and replace it in your msg() function.

If you need more replacements like this, you should find a template library that automates it.

 var input = document.querySelector("#scoresInput"); var msgWindow = document.querySelector("#msgWindow"); input.addEventListener("change", function() { if (this.value <= 0) { msg("errorMsg", 2); } else { msg("newMsg", 1); //wsDisplay.textContent = this.value; } }); var msgIndex = [ "new game begins now you play to {INPUTVALUE} scores", "you can't play to {INPUTVALUE} scores(", "! player 1 is the winner!", "! player 2 is the winner!" ]; function msg(msgClass, i) { msgWindow.classList.add(msgClass); msgWindow.textContent = msgIndex[i].replace('{INPUTVALUE}', input.value); } 
 <input id="scoresInput" type="number"> <button id="p1">player1</button> <button id="p2">player2</button> <button id="reset">newGame</button> <p id="msgWindow"></p> 

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