Javascript调用父/子窗体方法
在实际的编程中,有时我们需要在父窗体访问子窗体的方法或对子窗体进行访问、操作,又或者我们在子窗体内对父窗体进行访问或调用方法,实现很简单。见以下示例:
Code
父窗体(webform1.aspx):
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>父窗体</title>
<script type="text/javascript">
var Sys=function(){};
Sys.sayHello=function(){
alert('Hello parent/opner page!!');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<iframe id="ifm"></iframe>
<input type="button" onclick="document.getElementById('ifm').src='webform2.aspx'; //window.open('webform2.aspx')" value="Open Child" />
<input type="button" onclick="window.frames['ifm'].Sys.sayHello()" value="Invoke Child Domain" />
</form>
</body>
</html>
子窗体(webform2.aspx):
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>子窗体</title>
<script type="text/javascript">
var Sys=function(){};
Sys.sayHello=function(){
alert('Hello child page!!');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="button" value="Invoke Parent/Opner Domain" onclick="window.parent.Sys.sayHello();" />
</form>
</body>
</html>
父窗体(webform1.aspx):
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>父窗体</title>
<script type="text/javascript">
var Sys=function(){};
Sys.sayHello=function(){
alert('Hello parent/opner page!!');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<iframe id="ifm"></iframe>
<input type="button" onclick="document.getElementById('ifm').src='webform2.aspx'; //window.open('webform2.aspx')" value="Open Child" />
<input type="button" onclick="window.frames['ifm'].Sys.sayHello()" value="Invoke Child Domain" />
</form>
</body>
</html>
子窗体(webform2.aspx):
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>子窗体</title>
<script type="text/javascript">
var Sys=function(){};
Sys.sayHello=function(){
alert('Hello child page!!');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="button" value="Invoke Parent/Opner Domain" onclick="window.parent.Sys.sayHello();" />
</form>
</body>
</html>