JavaScript 提供了三种基本的浏览器交互方法,它们都是浏览器窗口方法(window
对象的方法),可以省略window.
前缀直接调用。
alert
显示一个带有消息和"确定"按钮的模态对话框。
alert("Hello, world!");
特点:
undefined
prompt
显示一个带有消息、输入框和"确定"/"取消"按钮的对话框。
let result = prompt("What's your name?", "Guest");
参数:
特点:
null
""
confirm
显示一个带有消息和"确定"/"取消"按钮的对话框。
let isOk = confirm("Are you sure?");
特点:
true
false
let age = prompt("How old are you?", 18);
if (age === null) {
alert("You cancelled.");
} else if (age === "") {
alert("You entered nothing.");
} else {
let confirmed = confirm(`You entered ${age}. Is this correct?`);
alert(confirmed ? "Confirmed!" : "Not confirmed.");
}