您的位置:首页 > Web前端 > JavaScript

javascript调用父窗口的函数和变量

2009-09-15 12:45 281 查看

javascript调用窗口的函数和变量

发布日期:2008-05-28最近更新:2008-05-28来源:BHCODE作者:

web开发的时候,有时候需要使用其他页面上写好的javasript函数、变量。如弹出窗口需要使用窗口中的函数,框架1需要使用框架2中的函数。

调用函数、变量的方法一样,都是需要首先获得你需要调用的函数所在的window对象,然后通过window.method()或者 window.variable 来调用。

下面的示例演示了一个弹出窗口如何调用起窗口中的方法和变量

窗口:1.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script type="text/javascript">
var theHelloStr = "Hello all.";

function sayHello()
{
alert("hello, method");
}

function openBtnClicked()
{
var newwin=window.open('2.html',"test","toolbar=no,location=no,top=100,left=100,directories=no,status=yes,menubar=no,scrollbars=yes,location=no,resizable=yes,width=300,height=200");
newwin.focus();
}

function sayHello2()
{
window.sayHello();
}
</script>
</head>

<body>
<input type="button" name="openBtn" value="打开窗口" onclick="openBtnClicked()" />
</body>
</html>



弹出窗口:2.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script type="text/javascript">
function btn1Clicked()
{
window.opener.sayHello();
}

function btn2Clicked()
{
var helloMsg = window.opener.theHelloStr;
alert(helloMsg);
}
</script>
</head>

<body>
<input type="button" name="btn1" value="调用窗口的方法" onclick="btn1Clicked()" />
<input type="button" name="btn2" value="调用窗口的变量" onclick="btn2Clicked()" />
</body>
</html>

说明:在2.html中,通过window.opener来获取弹出窗口的窗口的window对象。

反向思考:在一个页面中,也可以通过window.method()或者 window.variable来使用方法或者变量,例如1.html中的function sayHello2(){window.sayHello();},只是由于window是默认的对象,所以根本不需要加上。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐