JavaScript 弹出框
JavaScript 有三种类型的弹出框:警告框、确认框和提示框。
确认框
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript 确认框</h1>
<button onclick="myFunction()">试一试</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
// confirm() 方法用于显示一个带有指定消息和 OK 及取消按钮的对话框。
// confirm(message)
if (confirm('Press a button!')) {
txt = '您按了确定';
} else {
txt = '您按了取消';
}
document.getElementById('demo').innerHTML = txt;
}
</script>
</body>
</html>
警告框
window.alert() 方法可以不带 window 前缀来写。
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript 警告框</h1>
<button onclick="myFunction()">试一试</button>
<script>
function myFunction() {
alert('我是一个警告框!');
}
</script>
</body>
</html>
提示框
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Prompt</h1>
<button onclick="myFunction()">试一试</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
// prompt() 方法用于显示可提示用户进行输入的对话框。
// prompt(text,defaultText)
var person = prompt('请输入您的名字:', '哈利波特');
if (person == null || person == '') {
txt = '用户取消输入';
} else {
txt = '你好,' + person + '!今天过得好吗?';
}
document.getElementById('demo').innerHTML = txt;
}
</script>
</body>
</html>