目录

ES6 - 对话框( Dialog Boxes)

JavaScript支持三种重要类型的对话框。 这些对话框可用于提升和警告,或确认任何输入或从用户那里获得一种输入。 在这里,我们将逐一讨论每个对话框。

警报对话框

警报对话框主要用于向用户发送警告消息。 例如,如果一个输入字段需要输入一些文本但用户不提供任何输入,那么作为验证的一部分,您可以使用警告框发送警告消息。

尽管如此,警报框仍可用于更友好的消息。 警报框只提供一个“确定”按钮来选择并继续。

例子 (Example)

<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> 

成功执行上述代码后,将显示以下输出。

新页面打开

确认对话框

确认对话框主要用于征得用户对任何选项的同意。 它显示一个带有两个按钮的对话框:确定和取消。

如果用户单击“确定”按钮,则窗口方法confirm()将返回true。 如果用户单击“取消”按钮,则confirm()返回false。 您可以使用如下确认对话框。

例子 (Example)

<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()的方法显示,该方法采用两个参数:(i)要在文本框中显示的标签和(ii)要在文本框中显示的默认字符串。

此对话框有两个按钮:确定和取消。 如果用户单击“确定”按钮,则窗口方法提示符()将从文本框中返回输入的值。 如果用户单击“取消”按钮,则窗口方法prompt()将返回null。

例子 (Example)

<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> 

成功执行上述代码后,将显示以下输出。

新页面打开
↑回到顶部↑
WIKI教程 @2018