Prompt return as undefined in a function. (scope i

2019-08-28 21:25发布

问题:

I believe it's a scope issue because I tried setting my function userPrmpt inside firstPartCook and it works. I set it outside, and it doesn't. So it's reading, but not keeping what is returned. I thought by placing it in the test var that it would work, but it doesn't.

Here's my code

HTML

<!DOCTYPE html>
<html>
 <head>
  <title> Race Makin' </title>
  <!-- Link to the JS portion for this script -->
  <script src="riceMakin.js"></script>
 </head>
 <body>
  <!-- not going for anything fancy. Just focusing on mechanics -->
  <h1>Lets cook some damn rice</h1>
  <h2> To start cooking Rice, please hit start</h2>
  <button onclick="firstPartCook()">Start</button>
  <h3>Below explains the status on the Rice Making Machine:</h3>
  <!-- with JS i have what is inbetween the spans, switching from on and off -->
  <p id="print">Status: Turned <span id="print">Off</span> </p>     
 </body>
</html>

JS

//Global Vars here
//Promp for the User to continue throught the script. To use what is returned, set to a var
function userPrmpt(userResponse) {
   prompt(userResponse);
}

// This function is for adding type to the DOM.
function insertCopy (copy) {
   var paragraphCreate = document.createElement("p");
   var copyNode = document.createTextNode(copy);
   paragraphCreate.appendChild(copyNode);
   var idSelecter = document.getElementById("print");
   //print is the id tag of the span 
   idSelecter.appendChild(paragraphCreate);
}

//This is where we start working on the mechanics of the script    
function firstPartCook() {
   //var userAnswer = prompt("Welcome to the Rice Maker, want to start making rice?");
   var test = userPrmpt("Hello");
   if (test == "yes") {
      console.log(test);
      insertCopy("It worked");
   } else {
      console.log(test);
      insertCopy("Nope");
   }
}

回答1:

You have to return the value from the prompt, otherwise the function will just return undefined, which is the default return value of any function that has no other value returned from it

function userPrmpt(userResponse){
    return prompt(userResponse);
}