JS子窗体与父窗体相互调用 (转)

一、先说从父窗体传递参数到子窗体中

1.父窗体可以通过URL重写传递参数到子窗体,这也是最常用的方式。强烈建议将查询字符串用encodeURI()方法编码。

2.父窗体可以直接调用子窗体的函数将参数传递过去,不过这样传递参数得有个前提,就是当父窗体调用子窗体中的函数时,必须保其已经成功载入,否则调用不成功。

详细代码如下:

父窗体:

<HEAD>

<SCRIPT LANGUAGE="JavaScript">
<!--
function invokeChildren()
{
var children=open("children.html","","");
children.window._childrenTest('haha')

//此处的window可以省略掉
}
//-->
</SCRIPT>
</HEAD>

<BODY>
<button onClick="invokeChildren();">transfer</button>

</BODY>

子窗体:

<SCRIPT LANGUAGE="JavaScript">
<!--
function _childrenTest(value)
{

alert("parentValueIs="+value);
}
//-->
</SCRIPT>

显示结果:

parentValueIs=haha

二、从子窗体中将参数回传到父窗体中

父窗体中存在函数

function test(str)
{
    alert(str);
}

在子窗体中就可以用如下方法调用

// window.opener为父窗体的引用

window.opener.window.test("aaaa");

// 此处的第二个window不可以省(我也是百思不得其解)

在父窗体中有id为objid的DOM对象;

在子窗体中就可以用如下语句得到该对象

window.opener.document.getElementById("objid");

// 此处的document不可以省

NOTE:未在火狐下测试...

--------------------------------------------------------------------------个人测试

父页面:

function Send()
        {
           var FromChild=open("jstest2.aspx");
           //FromChild.InitFromParent("i am your parent");
           FromChild.document.getElementById("geted").value="i am your parent";
        }
       
        function GetFromChild(fromchild)
        {
            alert(fromchild);
        }
       

        function GoChild()
        {
            var child=window.open("jstest2.aspx");
        }
       
        function checktest()
        {
            if(document.getElementById("t1").value!="")
            {
                alert(document.getElementById("t1").value);
            }
        }

子页面:

function InitFromParent(GetParent)
    {
        //var geted=document.getElementById("geted");
        //geted.value=GetParent;
        alert(GetParent);
       
    }
   
   
    function GoBack(GO)
    {
        window.opener.window.GetFromChild(GO);
    }
   
    function ReloadParent()
    {
        //window.opener.opener=null;
        window.opener.location.reload();
    }
   
   
    function change()
    {
        window.opener.document.getElementById("t1").value="i am back";
    }

posted @ 2012-04-20 23:14  sidihu  阅读(609)  评论(0编辑  收藏  举报