2012-05-09 39 views
4

找到此代码以打印我修改的JavaScript元素。尽管我添加了document.title<title></title>标签,但在常规文本编辑器中打开的窗口显示为untitledJavaScript打印的窗口标题

这通常是保存文本之前的情况。无论如何,有没有办法显示标题?

var element=document.getElementById(element_id); 
    var newWin=window.open('','Print-Window','width=400,height=400,top=100,left=100'); 

    newWin.document.open(); 
    newWin.document.title = "Readings on PageLinks"; 
    newWin.document.write('<html><head><title>'+newWin.document.title+'</title></head><body onload="window.print()">'+element.innerHTML+'</body></html>'); 
    newWin.document.close(); 

    setTimeout(function(){ newWin.close(); },10); 
+1

为什么不?。newWin.document.write(” 读数上PageLinks ... –

+0

这并没有有所作为我有这样的第一 – user823527

+0

必须的有一些不同的东西或其他地方犯了一个错误,至少对于我的电脑来说是这样的 – Huangism

回答

1

我的猜测是,分配newWin.document.title = "Readings on PageLinks";失败,因为当时的页面没有<title>元素。

因此,newWin.document.title仍未定义。然后你把它连接到字符串<title>'+newWin.document.title+'</title>,所以它得到toString() -ed为“未定义”。

所以,只要直接写入标题到字符串

newWin.document.write('<html><head><title>Readings on PageLinks</title>...'); 

如伊兰棉兰的意见建议。

这对我有效。

+0

尽管如此,但再次阅读,标题是“无标题”,而不是“未定义”(例如,没有标题的窗口) –

2

其实原来的代码为我工作,以及(浏览器,其他浏览器上没有测试)

var element_id = "id1"; 
var element = document.getElementById(element_id); 
var newWin = window.open('', 'Print-Window', 'width=400,height=400,top=100,left=100'); 

newWin.document.open(); 
newWin.document.title = "Readings on PageLinks"; 
newWin.document.write('<html><head></head><body onload="window.print()">' + element.innerHTML + '</body></html>'); 
newWin.document.close(); 

setTimeout(function() { 
    newWin.close(); 
}, 10);​ 

查看JSFiddle

+0

没有在我的Opera上工作。标题是“about:blank”,显然是用空的url字符串打开页面的结果。不过,您以前的建议可以在Opera中使用。 – Imp

0

这可能是与打开的编辑器的行为文件。在保存文档之前,编辑器标题将会显示“未命名”。这必须通过设计。