JavaScript hint()基础教程文档

收录于 2023-04-20 00:10:05 · بالعربية · English · Español · हिंदीName · 日本語 · Русский язык · 中文繁體

JavaScript中的 prompt()方法用于显示提示框,提示用户进行输入。通常用于进入页面之前从用户那里获取输入。无需使用 window 前缀就可以编写它。弹出提示框时,我们必须单击"确定"或"取消"才能继续。
使用 prompt()方法显示该框,该方法带有两个参数:第一个参数是显示在文本框中的标签,第二个参数是默认字符串,显示在文本框中。提示框包含两个按钮, 确定取消。它返回null或用户输入的字符串。当用户单击"确定"时,该框将返回输入值。否则,在单击"取消"时返回null。
提示框将重点放在焦点上并强制用户阅读指定的消息。因此,应避免过度使用此方法,因为它会阻止用户访问网页的其他部分,直到关闭该框为止。

语法

prompt(message, default)

此函数的参数值定义如下。
message:是可选参数。它是向用户显示的文本。如果不需要在提示中显示任何内容,则可以忽略此值。
default:也是一个可选参数。它是一个包含在文本框中显示的默认值的字符串。
让我们看看 JavaScriptprompt()方法。

示例1

在此示例中,有一个简单的提示框,其中包含一条消息和两个按钮("确定"和"取消")。这里有一个HTML按钮,用于显示提示框。我们正在使用 onclick 属性,并调用定义了 prompt() fun()函数。
<html>
<head>
<script type = "text/javascript">
function fun() {
prompt ("This is a prompt box", "Hello world");
}
</script>
</head>
<body>
<p> Click the following button to see the effect </p>
<form>
<input type = "button" value = "Click me" onclick = "fun();" />
</form>
</body>
</html>
输出

Click the following button to see the effect

Example2

这是使用 prompt()方法的另一个示例。
<!DOCTYPE html>
<html>
<head>
<title>
JavaScript prompt() method
</title>
<script>
function fun() {
var a = prompt("Enter some text", "the lidihuo.com");
if (a != null) {
document.getElementById("para").innerHTML = "Welcome to " + a;
}
}
</script>
</head>
<body style = "text-align: center;">
<p style = "color: red;">
Hello World
</p>
<p>
Example of the JavaScript prompt() method
</p>
<button onclick = "fun()">
Click me
</button>
<p id = "para"></p>
</body>
</html>
输出

Hello World

Example of the JavaScript prompt() method

Example3

在此示例中,有一个带有消息和按钮的提示框。在这里,我们使用方框消息中的换行符。换行符是使用 '\ n'定义的。换行符使消息可读且清晰。我们必须单击给定的按钮才能看到效果。
<html>
   <head>
      <script type = "text/javascript">
    function fun() {
prompt(" Hello World \n Welcome to the lidihuo.com \n This is a prompt box ");
    }
      </script>
   </head>
   <body>
      <p> Click the following button to see the effect </p>
      <form>
 <input type = "button" value = "Click me" onclick = "fun();" />
      </form>
   </body>
</html>
输出

Click the following button to see the effect