我正在尝试找到几种不同的方法来添加事件监听器以监听来自 iFrame 的自定义事件。
我可以使用 jQuery 事件监听器成功监听来自 iFrame 的事件,但我似乎无法使用纯 JS 执行相同的操作。如果有人愿意看一下代码并让我知道我做错了什么,那就太好了。
iFrame 内部
(function(i,s,o){
// trigger load event for parent of iframe
parent.$('body').trigger('myevent:load');
// also trigger when everything is loaded, again
window.onload = function() {
parent.$('body').trigger('myevent:load');
}
})(window,document,$);
Iframe 容器(父级)
<script type="text/javascript">
<!--
// iFrame document resize script
function autoResize(id){
var newheight
, newwidth
, iframe;
if(document.getElementById){
iframe = document.getElementById(id);
newheight=iframe.contentWindow.document .body.scrollHeight;
newwidth=iframe.contentWindow.document .body.scrollWidth;
}
iframe.height= (newheight) + "px";
iframe.width= (newwidth) + "px";
};
// add event cross browser
function addEvent(elem, event, fn) {
// avoid memory overhead of new anonymous functions for every event handler that's installed
// by using local functions
function listenHandler(e) {
var ret = fn.apply(this, arguments);
if (ret === false) {
e.stopPropagation();
e.preventDefault();
}
return(ret);
}
function attachHandler() {
// set the this pointer same as addEventListener when fn is called
// and make sure the event is passed to the fn also so that works the same too
var ret = fn.call(elem, window.event);
if (ret === false) {
window.event.returnValue = false;
window.event.cancelBubble = true;
}
return(ret);
}
if (elem.addEventListener) {
elem.addEventListener(event, listenHandler, false);
} else {
elem.attachEvent("on" + event, attachHandler);
}
}
// listen for load event from iFrame
addEvent(document, 'myevent:load', function(){
// doesn't work
console.log("IFRAME LOADED! 2");
});
document.addEventListener('myevent:load', function(){
// also doesn't work
console.log("IFRAME LOADED! 1");
});
$(document).bind('myevent:load', function(){
// works
console.log("IFRAME LOADED! - jQuery");
});
//-->
</script>
最佳答案
在这里,您的事件是在正文上触发的,因此您应该监听正文上的事件,而不是文档上的事件:
document.querySelector("body").addEventListener("myevent:load",function() {
console.log("Hello");
},false);
语法:https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener
关于javascript - 检测来自 iframe 的事件与父级上的 jQuery 事件监听器一起使用,但现在使用纯 JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18464635/