Window prompt() 方法
实例
显示提示框,询问用户姓名,并输出消息:
<!DOCTYPE html><html><body><p>单击按钮以演示提示框。</p><button onclick="myFunction()">试一试</button><p id="demo"><script>function myFunction() {var person = prompt("输入你的姓名", "Harry Potter");if (person != null) {document.getElementById("demo").innerHTML ="Hello " + person + "! 你今天怎么样?";}}</script></body></html>
定义与用法
prompt() 方法显示一个对话框,提示访问者进行输入。
如果希望用户在进入页面之前输入值,则通常使用提示框。
注意:当弹出提示框时,用户在输入输入值后必须单击 "确定" 或 "取消" 才能继续。不要过度使用此方法,因为它会阻止用户在关闭框之前访问页面的其他部分内容。
如果用户单击 "确定",prompt() 方法将返回输入值。如果用户单击 "取消",则该方法返回 null。
浏览器支持
| 方法 | |||||
|---|---|---|---|---|---|
| prompt() | Yes | Yes | Yes | Yes | Yes |
语法
prompt(text, defaultText)
参数值
| 参数 | Type | 描述 |
|---|---|---|
| text | String | 必填。 The text to display in the dialog box |
| defaultText | String | 可选。 The default input text |
技术细节
| 返回值: | 一个字符串。如果用户单击 "确定",则返回输入值。如果用户单击 "取消",则返回 null。如果用户单击 "确定" 而未输入任何文本,则返回空字符串 |
|---|
更多实例
实例
使用 switch 语句和 prompt() 根据用户输入执行代码块:
<!DOCTYPE html><html><body><p>单击按钮可显示一个对话框,询问您最喜欢的饮料。</p><button onclick="myFunction()">试一试</button><p id="demo"><script>function myFunction() {var text;var favDrink = prompt("你最喜欢的鸡尾酒是什么?", "Daiquiri");switch(favDrink) {case "Martini":text = "很好的选择。Martini 对你的灵魂有好处。";break;case "Daiquiri":text = "Daiquiri 也是我的最爱!";break;case "Cosmopolitan":text = "真的吗? 你确定 Cosmopolitan 是你最喜欢的鸡尾酒?";break;default:text = "我从没听过这种鸡尾酒..";}document.getElementById("demo").innerHTML = text;}</script></body></html>
相关页面
Window 对象: alert()方法
Window 对象: confirm()方法