window.opener调用函数给我一个document.getElementById(...)为null

时间:2013-12-02 05:41:13

标签: javascript

我在父窗口上有以下代码

父窗口

<script type="text/javascript">

//Pop-up call 
 function show_popup()
    {
        var f = window.open("./show_my_popup.php", "mytitle", "width=550, height=500, scrollbars=yes");
    }

 //Call Back from Child Window function


  function GetChildWindowInfo(myval)
   {
    document.getElementById('selecteditem').value = myval;

   }
 </script>

这是将代码传递给父窗口

的代码的子窗口部分

子窗口

//Drop down Menu

<select id='selecteditem' name='select_item'>

<?php
foreach($each_query_item as $key => $value) {
echo "  <option value='$value' ";
if($_POST['select_item] == $key) echo "selected";
echo ">$value </option>\n";
}
?>

</select>

//Once you select item click here 

 <input type="button" name="submitbutton" value=<?php xl('Click Me','e','\'','\'');?> onclick="javascript:return SendValueToParent();" />


 <script type="text/javascript">

 function SendValueToParent()
{
    var myval = document.getElementById('selecteditem').value;
    window.opener.GetChildWindowInfo(myval);
    window.close();
    return false;
}

</script>

当我在父窗口上发出警报(myval)时,我得到了我传递的值; 但是,我得到了document.getElementById(...)为null。不明白为什么,请帮帮我。

1 个答案:

答案 0 :(得分:0)

也许您可以使用跨文档消息:

子窗口:

function SendValueToParent()
{
    var myval = document.getElementById('selecteditem').value;
    window.opener.postMessage(myval, "http://example.com");
    window.close();
    return false;
}

父窗口:

window.addEventListener("message", function(e){
        if(e.origin === "http://example.com/"){
            if(e.data){
                document.getElementById('selecteditem').value = e.data;
            }
        }
    }, false);