javascript 在子窗口中访问父局部变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26864359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:36:39  来源:igfitidea点击:

Access parent local variable in child window

javascriptphpglobal-variablesparent-child

提问by mOna

I would like to use a local variable of a parent in child window. I used parent.window.openerbut it returns undefined.

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

This is my code:

这是我的代码:

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

and this is a child:

这是一个孩子:

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

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

 </script>
</body>

回答by max

You can't - the whole idea with local variables is that they are only available in whatever function scope they are declared in - and functions inside that function.

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

In your case select selectedValis only available inside this function declaration:

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

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

To use it outside this scope you need to make it global by attaching it to the window:

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

window.selectedVal = 'somevalue';

You can also make variables implicitly global by leaving out the varkeyword - however this is a poor practice and is not allowed in strict mode.

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

This will allow you to you access window.selectedValby:

这将允许您window.selectedVal通过以下方式访问:

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

回答by Vano Atabegashvili

try this:

试试这个:

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

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

    </script>
</body>