可以在javascript中创建三种消息框:警告框、确认框、提示框。
警告框
警告框通常用于确保用户可以得到某些消息。
当警告框出现后,用户需要点击确定按钮才能继续进行操作。
语法:
alert(‘文本’);
确认框
确认框可以使用户验证或者接受某些信息。
当确认框出现后,用户需要点击确定或者取消按钮才能继续进行操作。
如果用户点击确认,那么返回true ,如果用户点击取消,那么返回false 。
语法:
confirm(‘文本’);
提示框
提示框经常用于提示用户进入页面前输入某个值。
当提示框出现后,用户需要输入某个值,点击确定或者取消按钮才能继续操作。
如果用户点击确定按钮,返回值为用户输入的值,如果用户点击取消按钮,返回值为null 。
语法:
prompt(‘文本’,’输入框中默认值’);
某些浏览器,如Chrome,IE javascript消息框右上角都带有关闭按钮
警告框中 点击关闭按钮 作用等同于点击确定按钮
确认框中 点击关闭按钮 作用等同于点击取消按钮
提示框中 点击关闭按钮 作用等同于点击取消按钮
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>javascript消息框</title>
</head>
<body>
<input id="alertBtn" type="button" value="警告框" />
<input id="alertBtn2" type="button" value="带有转折行的警告框" />
<input id="confirmBtn" type="button" value="show a confirm box" />
<input id="promptBtn" type="button" value="提示框" />
</body>
</html>
<script type="text/javascript">
var alertBtn = document.getElementById('alertBtn');
alertBtn.onclick = function () {
alert('我是警告框');
};
var alertBtn2 = document.getElementById('alertBtn2');
alertBtn2.onclick = function () {
alert('再次向您问好,我是很长很长的警告框,再次向您问好,我是很长很长的警告框,再次向您问好,我是很长很长的警告框,再次向您问好,我是很长很长的警告框');
alert('再次向您问好,\n我是主动换行的警告框');
};
var confirmBtn = document.getElementById('confirmBtn');
confirmBtn.onclick = function () {
if (confirm('press a button')) {
alert('You pressed OK !');
} else {
alert('You pressed Cancel !');
}
};
var promptBtn = document.getElementById('promptBtn');
promptBtn.onclick = function () {
var name = prompt('请输入您的名字', 'Bill Gates');
if (name != null && name != '') {
alert('您好,'+name+',今天过的怎么样?');
}
};
</script>