javascript - 函数中提示返回未定义。 (范围问题)

标签 javascript function scope undefined prompt

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

这是我的代码

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

最佳答案

您必须从提示中返回值,否则该函数将仅返回undefined,这是任何没有其他值返回的函数的默认返回值

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

关于javascript - 函数中提示返回未定义。 (范围问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24975899/

相关文章:

mysql - MySQL 中的generate_series

R. 尝试将元素分配给该对象时未找到对象错误

javascript - 变量范围

javascript - 如何使用reactjs向数组添加多个项目

javascript - 检查用户是否在 node.js 中的 postgresql 中(异步)

javascript - 日期格式转换自 2011-09-24T00 :00:00 to DD/MM/YYYY

c++ - 在对象超出范围之前调用的析构函数

javascript - C++、Qt、QtWebKit : How to create an html rendering window so that your application would get callbacks from JS calls?

function - SQlite 3.8.8 SPACE()函数替代

c++ - 将数学表达式传递给函数