访问子窗口中的父局部变量


Access parent local variable in child window

我想在子窗口中使用父窗口的局部变量。我使用了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>

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

在您的情况下,选择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

试试这个:

<body>
    <script type="text/javascript">
        var selectedVal = window.opener.selectedVal; 
        alert(selectedVal);
    </script>
</body>