2015-08-21 43 views
-1

我正嘗試使用window.open與動態內容(用於打印功能,我正在使用此動態內容)打開一個新窗口。 在動態HTML下方,window.open頁面上不可見,其中在視圖源中可用。請幫我解釋爲什麼它沒有顯示在那裏。Window.open在添加iframe標記後不顯示任何內容

下面是代碼。

var win = window.open('', 'title', 'toolbar=0,location=0,menubar=0,resizable=yes,width=' + (screen.width - 100) + ', height=' + (screen.height - 150)); 

win.document.write("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"); 

win.document.write("<html>"); 
win.document.write("<head><title>title</title>"); 
win.document.write('<script language="javascript" type="text/javascript">function printPage() { PrintDiv("defaultPrintBuffer"); }<\/script>'); 
win.document.write('</head>'); 

win.document.write('<body>'); 

win.document.write("<iframe width='560' height='315' id='defaultPrintBuffer2' name='defaultPrintBuffer2'>"); 
win.document.write(iframeContent); 
win.document.write("</iframe>"); 
win.document.write('</body>'); 

win.document.write("</html>"); 

win.document.close(); 

win.focus(); 
win.printPage(); 
+0

您可以將您正在創建的新頁面的所有靜態部分放在單獨的html文件中並打開該文件。這樣您就不必使用document.write,只需按常規方式設置iframe的url或內容即可。但要回答您的問題,您的腳本標記沒有正確關閉:'<\/script>' – Shilly

+0

我已經使用jquery生成了iframe,iframe src中沒有url。我正在實現打印功能並試圖實現使用IFrame。 – user2078643

回答

1

既然你提到你正在嘗試實現打印,我會添加如何解決這個問題的答案,而不是評論,所以代碼更具可讀性。 基本上我做了一個空的(但有效的)html頁面,並在打印之前將節點插入該頁面。這樣可以避免使用document.write和iframe,這在很多情況下被認爲是不好的做法。如果您確實想要使用iframe,只需將iframe添加到打印頁面html並將您的內容附加到該節點而不是正文。

var data = $('myPartOfPageSelector'), 
    printPage; 
if (!data || !data.length) alert('Nothing to print.'); 
else { 
    printPage = window.open('resources/print.html'); 
    setTimeout(function() { 
     printPage.document.body.innerHTML = data.innerHTML; 
     printPage.print(); 
     printPage.close(); 
    }, 100); 
} 
+0

非常感謝你爲這個解決方案,它似乎工作,但請建議我如何在print.html中添加iframe,因爲我會給打印的iframe不完整的頁面。 – user2078643

+0

這是完美的答案。非常感謝。 – user2078643

1

iframe標籤並不表明你把它的內容,你必須在iframe中加載的頁面。

你可以使用腳本來把內容在iframe:

win.document.write("<iframe width='560' height='315' id='defaultPrintBuffer2' name='defaultPrintBuffer2'>"); 
win.document.write("</iframe>"); 
win.document.write("<script type='text/javascript'>var doc = document.getElementById('defaultPrintBuffer2').contentWindow.document;doc.open();doc.write('" + iframeContent.replace("'","\\'").replace("\\","\\\\") + "');doc.close();</script>"); 

注意,內容應該是本身就是一個完整的HTML文檔。

+0

這是拋出一個錯誤 TypeError:doc.write不是一個函數 – user2078643

+0

@ user2078643:我錯過了'.document'在最後從窗口中獲取文檔對象。我更新了上面的代碼。 – Guffa