javascript - 检测来自 iframe 的事件与父级上的 jQuery 事件监听器一起使用,但现在使用纯 JS

标签 javascript jquery html iframe

我正在尝试找到几种不同的方法来添加事件监听器以监听来自 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/

相关文章:

javascript - 具有多种模式的 ng-file-upload

javascript - jQuery ajax 调用同步还是异步?

jquery - 如何检查bootstrap的jquery-plugin是否正常工作?

html - CSS 垂直对齐 : middle not working as expected

javascript - jquery 在勾选复选框之前不提交表单

html - 使用 CSS 在表单中定位元素

javascript - 从angularjs中的验证中删除最后一个ng-form

javascript - React .map() 不是函数错误

javascript - 一个事件处理程序中的引用变量,另一个事件处理程序中的引用变量

javascript - 输出包含 3 个单词的字符串中的前 2 个单词