Javascript 在刚刚附加iframe之后访问它

Javascript 在刚刚附加iframe之后访问它,javascript,jquery,Javascript,Jquery,我的版本不起作用: $(window).on('load', function() { var $iframe = $("<iframe>", {id:"up2europe", marginheight:"5", marginwidth:"5", src:"https://www.up2europe.eu/widget/go/181d

我的版本不起作用:

 $(window).on('load', function() {
      var $iframe = $("<iframe>", 
                 {id:"up2europe",
                 marginheight:"5",
                 marginwidth:"5",
                 src:"https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d"
                 }); 

       $(".sidebar__right:first").append($iframe).on('load', function() 
             alert(document.getElementbyId("#up2europe").documentElement.title);                                                                                                
       });
});

所以。。。我正在尝试访问iframe的标题…以检查它是否正确加载。

我认为这是使用jQuery添加元素的正确方法。看看这个

代码:


您的代码还有很多错误:

使用$..追加$iframe,返回$。。。在添加iframe之后。这意味着您的加载事件已附加到$。。。而不是iframe,在这种情况下,iframe是合乎逻辑的。要实现这一点,请使用$iframe.appendTo…,以便该方法的返回值为$iframe

在前面提到的加载事件侦听器中使用getElementbyId,这基本上是编写getElementbyId的错误方法

在事件侦听器中传递给alert的参数不是获取iframe文档标题的有效方法

因此,通过纠正上述错误,代码变为:

$(window).on('load', function() {
  /* Create the iframe. */
  var $iframe = $("<iframe>", {
    id: "up2europe",
    marginheight: "5",
    marginwidth: "5",
    src: "https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d"
  });

  /* Using 'appendTo' ensures we add the 'load' event listener to the iframe. */
  $iframe.appendTo(".sidebar__right:first").on('load', function() {
    /* 'this' refers to the iframe. */
    alert(this.contentDocument.title);
  });

getElementbyIdup2europe在getElementbyIdgetElementbyIdup2europe中不是必需的。getElementbyIdup2europe也需要是getElementbyIdup2europe{此处缺少:-$。侧边栏_right:首先。追加$iframe。在'load'上,您从哪个函数调用此代码https://www.up2europe.eu? 如果没有,您将运行相同来源的策略。当您修复所有的打字错误时。getElementbyIdup2europe不起作用。但在问题中,他说要检查它是否正确加载。而我没有知道他试图获取内容标题的哪一部分。此外,这甚至不是检查iframe是否已加载的正确方法。最好的方法是postMessage和receiveMessage方法,但只有当加载的框架是您的并且您可以在其中添加postMessage脚本时,它才可用。@AngelPolitispostMessage和receiveMessage用于跨社区iframe元素之间的交互;您不需要它们来检查iframe是否已加载,也不需要它是您的。一个简单的$iframe.load就足以检查其内容是否已加载。如果您的目的是操纵其内容,它只需要是您的。您可以检查iframe是否已添加,但无法检查src链接是否已加载在没有postMessage方法的情况下,已在内部编辑并完全准备就绪,是的,必须由您在其中添加js代码,以使源代码将消息发布到父窗口。@AngelPolitis您完全错了!一个简单的示例就足以向您展示了。加载事件就是这样做的;它检查元素的内容是否已加载。postMessage和receiveMessage A重新用于不同窗口之间的交叉通信。这是我的问题,加载方法不起作用。cr8code.co是我的,我试图在成功加载iframe后停止父窗口上的动画,但我无法进行加载。这就是为什么我声称最好的方法是:postMessage。@AngelPolitis
$(window).on('load', function() {
  /* Create the iframe. */
  var $iframe = $("<iframe>", {
    id: "up2europe",
    marginheight: "5",
    marginwidth: "5",
    src: "https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d"
  });

  /* Using 'appendTo' ensures we add the 'load' event listener to the iframe. */
  $iframe.appendTo(".sidebar__right:first").on('load', function() {
    /* 'this' refers to the iframe. */
    alert(this.contentDocument.title);
  });