javascript - Problem with parent page listening to events in iframe
世界只因有你
世界只因有你 2017-05-16 13:35:56
0
4
866

Can't be monitored all the time. What's the reason?

parent.html

<body>
    <iframe id="iframe" src="son.html" frameborder="0"></iframe>

<script src="./jquery.js"></script>
<script>
    $(function(){
        $($('#iframe')[0].contentWindow).on('dosomething', function(){
            alert('接收到到iframe的事件');
        });
    });
</script>
</body>

son.html

<body>
    
    <h1>son</h1>
    <button id="button">trigger</button>

<script src="./jquery.js"></script>
<script>
    $(function(){
        $('#button').on('click', function(){
            $(window).trigger('dosomething');
        });
    });
</script>
</body>

Thanks!

Dont

I just found it when searching, it is also good, the compatibility is OK
MessengerJS
https://github.com/biqing/Mes...
Cross-document communication solution

世界只因有你
世界只因有你

reply all(4)
滿天的星座

son.html

 $(function(){
        $('#button').on('click', function(){
            window.parent.$(window).trigger('dosomething');
        });
    });

The event is defined in the jquery of the parent page. To trigger, the jquery of the parent page needs to be responsible for triggering.

I haven’t looked at the jquery source code for a long time. I searched for a long time and couldn’t find the corresponding content to explain.

漂亮男人

PostMessage can be used to communicate between pages.

Or just bind and handle events on the same page.

$('#iframe').contents().find('#button').on("click", function(){
    $(window).trigger('dosomething');
});
Peter_Zhu

The reason why it cannot be monitored is because when the parent page performs event binding through the on method, the event callback function is registered in the jquery object of the parent page. When the sub-page executes the trigger method, it will only look for the event callback registered in the jquery object of the sub-page. Therefore, after the event is triggered, the event callback function registered by the parent page cannot be executed because it cannot be found in the jquery object of the sub-page.

为情所困

Two jqs, two environments, are you sure there is no problem?

------The above is the original answer, and the following is my complaint after being reported -------

I would like to ask the person who reported me, two jq environments, is this the reason why you cannot trigger the event?
What is wrong with my answer? What is the reason for your report?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!