JavaScript - 對話方塊



JavaScript 支援三種重要的對話方塊型別。這些對話方塊可用於發出警告、獲取確認或獲取使用者輸入。我們將逐一討論每種對話方塊。

警告對話方塊

警告對話方塊主要用於向用戶發出警告資訊。例如,如果某個輸入欄位要求輸入文字,但使用者未提供任何輸入,則作為驗證的一部分,可以使用警告框來顯示警告資訊。

儘管如此,警告框仍然可以用於更友好的訊息。警告框只有一個“確定”按鈕供選擇和繼續。

示例

<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。您可以按如下方式使用確認對話方塊。

示例

<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()將返回文字框中輸入的值。如果使用者單擊“取消”按鈕,則視窗方法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>
廣告