TypeError: window.parent.updatepic 不是函数,当我尝试从 iframe 访问函数到他的

TypeError: window.parent.updatepic is not a function when i try to access function from iframe to his window's parent

本文关键字:函数 iframe 访问 parent window updatepic TypeError      更新时间:2023-09-26

我的页面中有一个iframe,在这个iframe中,我正在加载一个包含此Javascript代码的页面:

<script>
    var ready;
    ready = function() {
        window.parent.updatepic("#{@user.photo_url.to_s}")
    };
    $(document).ready(ready);
    $(document).on('page:load', ready);
</script>

包含我的 iframe 的页面有一个脚本如下:

var ready;
ready = function() {
  function updatepic(pic){
    $("#image").attr("src", pic);
  }
};
$(document).ready(ready);
$(document).on('page:load', ready);

正如您在上面的第一个代码示例中看到的:

 window.parent.updatepic("#{@user.photo_url.to_s}")

我尝试从 iframe 内部调用 updatepic 函数,但在控制台中出现错误:

TypeError: window.parent.updatepic is not a function

找不到或理解我在这里做错了什么?请帮忙。

窗口中的updatepic方法包装在闭包(您分配给ready变量的函数)中。因此,该函数在全局window命名空间中不可用。

updatepic的定义移到分配给ready的函数之外。