在函数中提示未定义返回.(问题)范围

Prompt return as undefined in a function. (scope issue)

本文关键字:问题 范围 返回 未定义 函数 提示      更新时间:2023-09-26

我认为这是一个范围问题,因为我试图在firstPartCook内设置我的函数userPrmpt并且它有效。我把它放在外面,它没有。所以它在读取,但不保留返回的内容。我认为通过把它放在测试变量,它会工作,但它没有。

这是我的代码

<!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");
   }
}

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

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