若是要确保信息传递给用户,一般会使用警告框。html
当警告框弹出时,用户将须要单击“肯定”来继续。spa
window.alert("sometext");
window.alert() 方法能够不带 window 前缀来写。code
alert("我是一个警告框!");
<!DOCTYPE html> <html> <body> <h1>JavaScript 警告框</h1> <button onclick="myFunction()">试一试</button> <script> function myFunction() { alert("我是一个警告框!"); } </script> </body> </html>
若是您但愿用户验证或接受某个东西,则一般使用“确认”框。htm
当确认框弹出时,用户将不得不单击“肯定”或“取消”来继续进行。blog
若是用户单击“肯定”,该框返回 true。若是用户单击“取消”,该框返回 false。ip
window.confirm("sometext");
window.confirm() 方法能够不带 window 前缀来编写。get
var r = confirm("请按按钮"); if (r == true) { x = "您按了确认!"; } else { x = "您按了取消!"; }
<!DOCTYPE html> <html> <body> <h1>JavaScript 确认框</h1> <button onclick="myFunction()">试一试</button> <p id="demo"></p> <script> function myFunction() { var txt; if (confirm("Press a button!")) { txt = "您按了肯定"; } else { txt = "您按了取消"; } document.getElementById("demo").innerHTML = txt; } </script> </body> </html>
若是您但愿用户在进入页面前输入值,一般会使用提示框。io
当提示框弹出时,用户将不得不输入值后单击“肯定”或点击“取消”来继续进行。function
若是用户单击“肯定”,该框返回输入值。若是用户单击“取消”,该框返回 NULL。class
window.prompt("sometext","defaultText");
window.prompt() 方法能够不带 window 前缀来编写。
var person = prompt("请输入您的姓名", "比尔盖茨"); if (person != null) { document.getElementById("demo").innerHTML = "你好 " + person + "!今天过的怎么样?"; }
<!DOCTYPE html> <html> <body> <h1>JavaScript Prompt</h1> <button onclick="myFunction()">试一试</button> <p id="demo"></p> <script> function myFunction() { var txt; var person = prompt("请输入您的名字:", "哈利波特"); if (person == null || person == "") { txt = "用户取消输入"; } else { txt = "你好," + person + "!今天过得好吗?"; } document.getElementById("demo").innerHTML = txt; } </script> </body> </html>
如需在弹出框中显示折行,请在反斜杠后面加一个字符 n。
alert("Hello\nHow are you?");
<!DOCTYPE html> <html> <body> <h1>JavaScript</h1> <p>在警告框中换行。</p> <button onclick="alert('Hello\nHow are you?')">试一试</button> </body> </html>