在函数中提示返回为undefined。 (范围问题)

时间:2014-07-26 21:59:24

标签: javascript function scope undefined prompt

我认为这是一个范围问题,因为我尝试在userPrmpt内设置我的函数firstPartCook并且它有效。我把它放在外面,但事实并非如此。所以它正在阅读,但不保留返回的内容。我想通过将它放在测试变量中它可以工作,但事实并非如此。

这是我的代码

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 个答案:

答案 0 :(得分:0)

你必须从提示符返回值,否则函数将只返回undefined,这是任何没有返回其他值的函数的默认返回值

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