HTML Dom or JavaScript programming language provides Window.prompt() which display a dialog with an optional message prompting the user to input some text. prompt() function is very useful for getting data from the user in real time or interactively. There are different ways to accomplish user data input from the browser but this is the simplest and easy way.
HTML Dom或JavaScript编程语言提供Window.prompt(),该对话框显示带有可选消息的对话框,提示用户输入一些文本。 提示()函数对于实时或交互地从用户获取数据非常有用。 有多种方法可以完成从浏览器输入用户数据的操作,但这是最简单易行的方法。
语法和参数 (Syntax and Parameters)
window.prompt()
function has the following syntax where we have two parameters named message
and default
window.prompt()
函数具有以下语法,其中我们有两个参数分别名为message
和default
result = window.prompt(message, default);
- `result` is the value input by the user interactively “结果”是用户交互输入的值
- `message` is the message which will be shown to the user with the input box“ message”是将在输入框中显示给用户的消息
- `default` is the value which will be set to the input by default.“ default”是默认情况下将设置为输入的值。
向用户显示消息 (Display Message To The User)
As stated previously we can display or present a message to the user during the input. We will use the message parameter. In this example, we will print the message "Please Enter Your Age"
.
如前所述,我们可以在输入过程中向用户显示或显示消息。 我们将使用message参数。 在此示例中,我们将打印消息"Please Enter Your Age"
。
let age = prompt("Please Enter Your Age");
调用和使用hint()函数的不同方法(Different Ways To Call and Use prompt() Function)
In the previous example, we have called prompt()
function directly. But there are different ways to call prompt() function those are described below. All of the following examples are the same and there is no difference.
在前面的示例中,我们直接调用了prompt()
函数。 但是,有以下几种不同的方法来调用hint()函数。 以下所有示例都是相同的,没有区别。
prompt("Please Enter Your Age");
window.prompt("Please Enter Your Age");
设置默认值显示输入字段 (Set Default Value Display Input Field)
prompt() function is mainly used to input or get a value from the user. In some cases, we may need to specify a default value which can be used by the user. We can specify the default value after the message. In this example, we will use default value 18 for the age.
hint()函数主要用于输入或从用户那里获取值。 在某些情况下,我们可能需要指定用户可以使用的默认值。 我们可以在消息后指定默认值。 在此示例中,我们将使用默认值18作为年龄。
prompt("Please Enter Your Age","18");
将输入转换为数字(Convert Input To Number)
prompt() function will read given value from the user and return as a string type in JavaScript. If the user clicks to the Cancel
button the returned value will be null
which means there is no value. We can convert the inputted value into a number with the Number
function which is used to convert a string to a number.
hint()函数将从用户读取给定值,并以JavaScript中的字符串类型返回。 如果用户单击“ Cancel
按钮,则返回的值将为null
,这意味着没有值。 我们可以使用Number
函数将输入的值转换为数字,该函数用于将字符串转换为数字。
const age=prompt("Please Enter Your Age");
翻译自: https://www.poftut.com/how-to-display-and-input-data-from-user-window-prompt-in-html-and-javascript/