简体   繁体   English

无法为iframe调用null的方法“ appendChild”

[英]Cannot call method 'appendChild' of null for iframes

I have the following script to create an iframe 我有以下脚本来创建iframe

  function createIframe() {
    var iframe = document.createElement("iframe");
    iframe.style.position = "absolute";
    iframe.style.visibility = "hidden";

    document.body.appendChild(iframe);

    // Firefox, Opera
    if(iframe.contentDocument) iframe.doc = iframe.contentDocument;
    // Internet Explorer
    else if(iframe.contentWindow) iframe.doc = iframe.contentWindow.document;

    // Magic: Force creation of the body (which is null by default in IE).
    // Also force the styles of visited/not-visted links.
    iframe.doc.open();
    iframe.doc.write('<style>');
    iframe.doc.write("a{color: #000000; display:none;}");   
    iframe.doc.write("a:visited {color: #FF0000; display:inline;}");    
    iframe.doc.write('</style>');
    iframe.doc.close();

    // Return the iframe: iframe.doc contains the iframe.
    return iframe;
  }  

however in chrome console it is giving me the error Cannot call method 'appendChild' of null 但是在chrome控制台中,它给我错误无法调用null的方法'appendChild'

why is it not working? 为什么它不起作用?

The code is correct. 代码正确。 Have you added body in the page? 您在页面中添加了正文吗?

Try this: 尝试这个:

<html>
<body>
<script>
window.onload=function() {
   createIframe()
};
function createIframe() {
    var iframe = document.createElement("iframe");
    iframe.style.position = "absolute";
    iframe.style.visibility = "hidden";

    document.body.appendChild(iframe);

    // Firefox, Opera
    if(iframe.contentDocument) iframe.doc = iframe.contentDocument;
    // Internet Explorer
    else if(iframe.contentWindow) iframe.doc = iframe.contentWindow.document;

    // Magic: Force creation of the body (which is null by default in IE).
    // Also force the styles of visited/not-visted links.
    iframe.doc.open();
    iframe.doc.write('<style>');
    iframe.doc.write("a{color: #000000; display:none;}");   
    iframe.doc.write("a:visited {color: #FF0000; display:inline;}");    
    iframe.doc.write('</style>');
    iframe.doc.close();

    // Return the iframe: iframe.doc contains the iframe.
    return iframe;
  }  
</script>
</body>
</html>

iframe.doc.write is not the cleanest solution.... iframe.doc.write不是最干净的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM