JavaScript popup
You can create three kinds of message boxes in JavaScript: warning box, confirmation box, and prompt box.
Alert box
Alert boxes are often used to ensure that users can get certain information.
When the warning box appears, the user needs to click the OK button to continue the operation.
grammar
window.alert() method can be used directly without the window object. alert( )method.
Instance
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> function myFunction(){ alert("你好,我是一个警告框!"); } </script> </head> <body> <input type="button" onclick="myFunction()" value="显示警告框" /> </body> </html>
Run instance»
Click the "Run instance" button to view the online instance
Confirmation box
Confirmation box is usually used to verify whether the user operation is accepted.
When the confirmation card pops up, the user can click "Confirm" or "Cancel" to confirm the user operation.
When you click "Confirm", the confirmation box returns true. If you click "Cancel", the confirmation box returns false.
grammar
window.confirm() The method can be used directly without the window object. confirm( )method.
Instance
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <p>点击按钮,显示确认框。</p> <button onclick="myFunction()">点我</button> <p id="demo"></p> <script> function myFunction(){ var x; var r=confirm("按下按钮!"); if (r==true){ x="你按下了\"确定\"按钮!"; } else{ x="你按下了\"取消\"按钮!"; } document.getElementById("demo").innerHTML=x; } </script> </body> </html>
Run instance»
Click the "Run instance" button to view the online instance
Prompt box
Prompt box is often used to prompt the user to enter a certain value before entering the page.
When the prompt box appears, the user needs to enter a certain value and then click the confirm or cancel button to continue the operation.
If the user clicks to confirm, the return value is the entered value. If the user clicks Cancel, the return value is null.
grammar
window.prompt() method can be omitted For window objects, use the prompt() method directly.
Instance
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <p>点击按钮查看输入的对话框。</p> <button onclick="myFunction()">点我</button> <p id="demo"></p> <script> function myFunction(){ var x; var person=prompt("请输入你的名字","Harry Potter"); if (person!=null && person!=""){ x="你好 " + person + "! 今天感觉如何?"; document.getElementById("demo").innerHTML=x; } } </script> </body> </html>
Run instance»
Click the "Run instance" button to view the online instance
Line break
The pop-up window uses backslash + "n" (\n) to set line break.
Instance
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <p>点击按钮在弹窗总使用换行。</p> <button onclick="myFunction()">点我</button> <p id="demo"></p> <script> function myFunction(){ alert("Hello\nHow are you?"); } </script> </body> </html>
Run instance»
Click the "Run instance" button to view the online instance