【问题标题】:window.opener call function gives me a document.getElementById(...) is nullwindow.opener 调用函数给了我一个 document.getElementById(...) is null
【发布时间】:2013-12-02 13:57:01
【问题描述】:

我在父窗口上有以下代码

父窗口

<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>

当我在父窗口上执行 alert(myval) 时,我得到了我传递的值; 但是,我得到 document.getElementById(...) 为空。不明白为什么,请帮帮我。

【问题讨论】:

  • 请发布实际的 HTML,而不是 PHP 代码。
  • 你在你的父母中得到document.getElementById(...) is null?父项中是否有 ID 为 selecteditem 的元素?另外,您可以尝试保持选择选项的“名称”和“ID”值相同吗?
  • 是的,null 来自父窗口。 'selecteditem' 来自子窗口的 id。我在关注一个例子hspinfo.wordpress.com/2008/01/17/…
  • 你真正想要做什么?首先调用window.opener.GetChildWindowInfo(myval); 并传递想要的值,然后在GetChildWindowInfo() 中尝试再次设置相同的值...如果您需要访问子窗口,则需要使用对它的引用:f.document.getElementById('selecteditem').value = myval;。虽然我不明白为什么要这样做,但selecteditem 的值已经是myval。此外,某些浏览器可能会忽略设置 select 元素的值。
  • 我只想获取所选值或 selecteditem 并几乎提取数字....我确实得到了 myval 因为我可以使用 alert 显示 myval .... 但我认为你必须再次获取 id,我得到 null,因为它是来自子窗口的 id。

标签: javascript


【解决方案1】:

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

子窗口:

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);

【讨论】:

    猜你喜欢
    • 2014-10-13
    • 2012-12-02
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 2014-11-12
    相关资源
    最近更新 更多