ES6 - 對話方塊



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> 

以上程式碼成功執行後,將顯示以下輸出。

alert dialogue box

確認對話方塊

確認對話方塊主要用於獲取使用者對任何選項的同意。它顯示一個帶有兩個按鈕的對話方塊:確定和取消。

如果使用者單擊“確定”按鈕,則視窗方法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> 

以上程式碼成功執行後,將顯示以下輸出。

confirmation dialogue box

提示對話方塊

當您想要彈出一個文字框以獲取使用者輸入時,提示對話方塊非常有用。因此,它使您能夠與使用者互動。使用者需要填寫該欄位,然後單擊“確定”。

此對話方塊是使用稱為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> 

以上程式碼成功執行後,將顯示以下輸出。

prompt dialogue box
廣告

© . All rights reserved.