JavaScript popup
JavaScript pop-up window
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.
Syntax
window.alert("sometext");
window.alert() method can be omitted For window objects, use the alert() method directly.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> function myFunction(){ alert("警告框!"); } </script> </head> <body> <input type="button" onclick="myFunction()" value="显示警告框" /> </body> </html>
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.
Syntax
window.confirm("sometext");
window.confirm( ) method can use the confirm() method directly without the window object.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </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>
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.
Syntax
window.prompt("sometext","defaultvalue");
window.prompt() method can be used directly without the window object prompt() method.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </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>
Line break
Use backslash + "n"(\ n) to set line breaks.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <p>点击按钮在弹窗总使用换行。</p> <button onclick="myFunction()">点我</button> <p id="demo"></p> <script> function myFunction(){ alert("Hello\nHow are you?"); } </script> </body> </html>