我怎样才能获得iframe元素?

时间:2017-08-05 13:47:36

标签: javascript jquery html iframe parent-child

这是main.html

<body>
    <iframe id="frame" src="frame.html"></iframe>
    <script type="text/javascript">
    document.getElementById('frame').contentWindow.document.getElementById('test').innerHtml = 'abcdefgh';
    </script>     
</body>

这是frame.html

<body>
    <p id="test">0123456798</p>
    <script type="text/javascript"></script>
</body>
  

错误:未捕获TypeError:无法设置null

的属性'innerHTML'

为什么不起作用,以及如何更改id="test"文字

2 个答案:

答案 0 :(得分:0)

使用setTimeout()延迟您的脚本。 iframe需要加载时间。

<iframe id="frame" src="frame.html"></iframe>
<script type="text/javascript">
setTimeout(function(){
  document.getElementById('frame').contentWindow.document.getElementById('test').innerHTML = 'abcdefgh';
},800);
</script> 

注意innerHTML()上的大写字母。

答案 1 :(得分:0)

您好,这里有解决方案



    setTimeout(function(){
        var iframe = document.getElementById('frame');
        console.log(iframe);
    });

希望有所帮助

相关问题