常用互动方法
1.输出内容 document.write(); 用法与cout很像。括号内写输出内容。
例如:
document.write(mystr+"I love JavaScript");
2.弹出警告框 alert();
在点击对话框"确定"按钮前,不能进行任何其它操作。
消息对话框通常可以用于调试程序。
alert输出内容,可以是字符串或变量,与document.write 相似
例如:
alert("hello!");
3.确认 confirm 对话框 confirm(str);
str是弹出对话框中显示的内容,对话框中有两个按钮;返回一个boolean值,确认返回ture,取消返回false;
在点击对话框按钮前,不能进行任何其它操作。
4.提问 prompt 对话框 prompt(str1,str2);
str1为对话框中显示的文本;str2为输入到文本框的值,可以省略str2不写,例如:
var myname=prompt("请输入你的姓名:");点击确定,返回值为文本框中值;点击取消返回null;
5.打开新窗口 window.open('url','name','param');
注意:
窗口名称:可选参数,被打开窗口的名称。 1.该名称由字母、数字和下划线字符组成。 2."_top"、"_blank"、"_self"具有特殊意义的名称。 _blank:在新窗口显示目标网页 _self:在当前窗口显示目标网页 _top:框架网页中在上部窗口中显示目标网页 3.相同 name 的窗口只能创建一个,要想创建多个窗口则 name 不能相同。 4.name 不能包含有空格。
mooc上的参数表:
window.open返回一个窗口对象。
6.关闭窗口 window.close();或者 ‘窗口对象’.close();
例如:
var mywin=window.open('http://www.imooc.com'); mywin.close();
7.练习
<!DOCTYPE html>
<html>
<head>
<title> new document </title>
<meta http-equiv="Content-Type" content="text/html; charset=gbk"/>
<script type="text/javascript">
function openwindow()
{
var ifopen;
var mlink;
// 新窗口打开时弹出确认框,是否打开
ifopen = confirm("确定打开窗口?");
if(ifopen != null)
{
mlink = prompt("请输入想跳转的网址:");
if (mlink == null)
mlink = 'http://www.imooc.com/';
window.open(mlink,'new_win','width = 400, height = 500,menubar = null,toolbar = null');
}
}
}
</script>
</head>
<body>
<input type="button" value="新窗口打开网站" onclick="openWindow()" />
</body>
</html>
示例代码:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>浏览器对象</title>
<script type="text/javascript">
function openWindon(){
if(confirm("确定打开新窗口吗?")){
var url = prompt("请输入一个网址","http://www.imooc.com/");
window.open( url,"_blank","toolbar=no, menubar=no, scrollbars=yes, width=400, height=400");
}
}
</script>
</head>
<body>
<input type="button" value="新窗口打开网站" onclick="openWindon()" />
</body>
</html>