重新加载后无法从子iframe自动调用js函数

时间:2019-02-15 08:57:35

标签: javascript html parent-child

我有一个基于php的网页,并且在iframe中有另一个网页。父级包含项目列表,而iframe包含将添加/编辑该列表,将其保存到DB并将js消息发送到父级页面(列表)至update list without reloading parent page的页面(这比这复杂一点,但是那是核心思想)。

//html parent page basic content
<head>
    <script>
        function alert_me(){
            alert('IT\'S ALIVE!');
        }
    <script>
</head>
<body>
    <iframe src='child_page.html'></iframe>
</body>

现在是子页面。

<head>
    <script>
        $(document).ready(function(){

            //this is not working and this is what I want (auto call function after reload child)
            window.top.alert_me();

            //I tried autoclick button but it's not working either
            $('.alert_me_button').trigger('click');

        }); 
    </script>
</head>
<body>
    <!-- this is working just fine, so I know the code itself is ok -->
    <a href="#" class="alert_me_button" onclick="window.top.alert_me();" >Click me to alert me</a>
</body>

如您所见,当用户单击按钮callij js funtion时,它工作正常,但不起作用,因为我不需要任何用户操作。我使用triend,documnt.ready()...甚至setInterval()来暂停脚本,以确保它不是计时问题。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

代码工作正常。 你使用的是什么浏览器。我只是复制了您的代码,并从CDN添加了jquery。我使用SimpleHttpServer来提供页面并避免跨源阻塞。

重新加载后,我在Chrome和Firefox中也收到了两次消息。