2013-04-20 95 views
0

調用方法「的appendChild」空的,我有以下腳本來創建一個iframe無法爲I幀

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; 
    } 

但是在Chrome控制檯這是給我的錯誤,無法調用空的方法「的appendChild」

爲什麼它不起作用?

+0

當你得到這個錯誤嗎?我在我的Chrome控制檯中運行了它,它工作正常!只需檢查'document.createElement(「iframe」);'返回一個元素! – NINCOMPOOP 2013-04-20 08:21:11

回答

0

該代碼是正確的。你有沒有在頁面中添加正文?

試試這個:

<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不乾淨的解決方案....