在子窗口中访问父本地变量

时间:2014-11-11 11:57:35

标签: javascript php global-variables parent-child

我想在子窗口中使用父级的局部变量。我使用parent.window.opener但它返回undefined

这是我的代码:                      

<script type="text/javascript">
 var selectedVal;

 $(document).ready(function () {
  //....
  //...
   if ($(this).val() == "byActor"){
           $("#tags").focus();
           $("#tags").autocomplete({
             source: "actorsauto.php",
             minLength: 2,
             focus: function( event, ui ){
                   event.preventDefault(); 
                   return false;
             },
             select: function (event, ui){ 
                       var selectedVal = ui.item.value;
                       alert(selectedVal);
                   }
            }); 
   });

$('#btnRight').on('click', function (e) {
         popupCenter("movieByactor.php","_blank","400","400");
});
</script>
 </body>
 </html>

这是一个孩子:

<body>
 <script type="text/javascript">

  var selectedVal = parent.window.opener.selectedVal; 
   alert(selectedVal);

 </script>
</body>

2 个答案:

答案 0 :(得分:8)

你不能 - 局部变量的整个想法是它们只在它们被声明的任何函数范围内可用 - 以及该函数内的函数。

在您的情况下,选择selectedVal仅在此函数声明中可用:

select: function (event, ui){ 
   var selectedVal = ui.item.value;
   alert(selectedVal);
}

要在此范围之外使用它,您需要通过将其附加到窗口来使其全局化:

window.selectedVal = 'somevalue';

您也可以通过省略var关键字来隐式全局变量 - 但是这是一种不好的做法,在严格模式下是不允许的。

这样您就可以通过以下方式访问window.selectedVal

window.opener.selectedVal // for windows opened with window.open()
window.parent.selectedVal // iframe parent document

答案 1 :(得分:-2)

试试这个:

<body>
    <script type="text/javascript">

        var selectedVal = window.opener.selectedVal; 
        alert(selectedVal);

    </script>
</body>