Javascript:如何在没有任何 HTML 的情况下获取用户输入并存储到变量中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21104869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: How do you take user input and store into a variable without any HTML?
提问by Beast_Code
I want to ask the user through the console to enter a number. I then want to store it into a variable to have it used for a function etc. Here is an example of what I have done. When i do this it says ReferenceError: readline is not defined
我想通过控制台要求用户输入一个数字。然后我想将它存储到一个变量中以将它用于函数等。这是我所做的一个例子。当我这样做时,它说 ReferenceError: readline is not defined
console.log("Enter your guess and press <Enter>: /t" );
var userNumber = readline();
I am just trying to create an interactive js console app for now.
我现在只是想创建一个交互式 js 控制台应用程序。
Edit: Here is my source code http://repl.it/NeI/4
编辑:这是我的源代码http://repl.it/NeI/4
回答by Alex Shilman
Try doing this:
尝试这样做:
var guess = window.prompt("Enter your guess", "Number from 1 to 9");
console.log(guess);
回答by Kelly J Andrews
The console does not do what you are hoping it will in this situation.
在这种情况下,控制台不会执行您希望的操作。
Hereis the API documentation from Mozilla, and hereare the Chrome docs.
这里是来自 Mozilla 的 API 文档,这里是 Chrome 文档。
The console intent is to display information from your application for debugging purposes, with some minor helper functions.
控制台的目的是为了调试目的显示来自您的应用程序的信息,以及一些次要的帮助函数。
回答by Alcides Queiroz Aguiar
Developer tools or Firebug console can't receive user data this way, there's no read
or readline
methods. You have to use a window method called "prompt"
.
开发者工具或 Firebug 控制台无法以这种方式接收用户数据,没有read
orreadline
方法。您必须使用名为"prompt"
.
var data = prompt("Type something to me baby!");
console.log(data);
Here'sanother question addressing this same doubt.