通过 iframeElement.contentDocument.body 访问时的

我在开发服务器上有一个非常简单的设置(两个页面都在我的本地测试服务器上localhost:5500),我有一个主页


<!DOCTYPE html>

<html>

<head>

  <title>Example Mockup</title>

</head>

<body>

  <iframe src="./nested.html" id="frame"></iframe>

  <script>

    var iframe = document.getElementById('frame');

    console.log(iframe.contentDocument.body);

  </script>

</body>

</html>

和一个嵌套页面


<html>

    <body>

        <div id="hello">Hello, World</div>

    </body>

</html>

当我在浏览器中加载主页时,写入控制台的输出是:<body></body> 我可以使用访问元素#hello,iframe.contentDocument.getElementById('hello')但我想要包含子元素的 body 元素。任何人都可以向我解释为什么会发生这种情况


守着一只汪
浏览 249回答 1
1回答

万千封印

您必须等到 iframe 完全加载才能访问它的主体。var iframe = document.getElementById('frame');iframe.onload = function () {&nbsp; &nbsp; console.log(iframe.contentDocument.body);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript