JavaScript支持三种重要类型的对话框,这些对话框可用于提示(Confirmation)和警告(Alert),或从用户那里获得某种输入(Prompt)。在这里,无涯教程将逐个讨论每个对话框。
alert对话框通常用于向用户提供警告消息,如果一个输入字段要求输入一些文本,但用户未提供任何输入,则作为验证的一部分,您可以使用alert框发出警告消息。
<html> <head> <script type = "text/javascript"> <!-- function Warn() { alert ("This is a warning message!"); document.write ("This is a warning message!"); } //--> </script> </head> <body> <p>Click the following button to see the result: </p> <form> <input type = "button" value = "Click Me" onclick = "Warn();" /> </form> </body> </html>
运行上面代码输出
确认对话框通常用于征得用户对任何选项的同意,它显示一个带有两个按钮的对话框:OK和NO。
如果用户单击"OK"按钮,则窗口方法 confirm()将返回true,如果用户单击"NO"按钮,则 confirm()返回false。您可以如下使用确认对话框。
<html> <head> <script type = "text/javascript"> <!-- function getConfirmation() { var retVal = confirm("Do you want to continue ?"); if( retVal == true ) { document.write ("User wants to continue!"); return true; } else { document.write ("User does not want to continue!"); return false; } } //--> </script> </head> <body> <p>Click the following button to see the result: </p> <form> <input type = "button" value = "Click Me" onclick = "getConfirmation();" /> </form> </body> </html>
运行上面代码输出
当您要弹出文本框以获取用户输入时,Prompt对话框非常有用,因此它使您可以与用户进行交互。用户需要填写该字段,然后单击"OK"。
使用名为 prompt()的方法显示此对话框,该方法具有两个参数:(i)您要在文本框中显示的标签,以及(ii)要在文本中显示的默认字符串框。
该对话框有两个按钮:OK和Cancel。如果用户单击"OK"按钮,则窗口方法 prompt()将从文本框中返回输入的值。如果用户单击"Cancel"按钮,则窗口方法 prompt()返回 null 。
以下示例显示如何使用提示对话框-
<html> <head> <script type = "text/javascript"> <!-- function getValue() { var retVal = prompt("Enter your name : ", "your name here"); document.write("You have entered : " + retVal); } //--> </script> </head> <body> <p>Click the following button to see the result: </p> <form> <input type = "button" value = "Click Me" onclick = "getValue();" /> </form> </body> </html>
运行上面代码输出
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)