首页 > 解决方案 > 重新加载后从子 iframe 自动调用 js 函数不起作用

问题描述

我有一个基于 php 的网页,其中iframe包含另一个网页。Parent 包含项目列表,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 功能时它工作正常,但它不会工作,因为我不想要任何用户操作。我尝试,documnt.ready()... 甚至 setInterval() 来暂停脚本以确保它不是时间问题。有任何想法吗?

标签: javascripthtmlparent-child

解决方案


代码工作得很好。你使用的是什么浏览器。我刚刚复制了您的代码并从 cdn 添加了 jquery。我使用 SimpleHttpServer 来服务页面并避免跨源阻塞。

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


推荐阅读