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
滿天的星座2017-05-16 13:37:56
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.
漂亮男人2017-05-16 13:37:56
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');
});
天蓬老师2017-05-16 13:37:56
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.
为情所困2017-05-16 13:37:56
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?