1

我试图找到几种不同的方法来添加事件侦听器以侦听来自 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>
4

1 回答 1

0

Here, your event is triggered on body, so you should listen for events on body, not document :

document.querySelector("body").addEventListener("myevent:load",function() {
    console.log("Hello");
},false);

Syntax : https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener

于 2014-02-24T18:01:13.663 回答