Javascript 如何打印字符串中的HTML数据
我的项目中有一个打印按钮。我正在使用JavaScript打印数据。我有一个变量作为data_to_print,它包含要打印的HTML。问题是,当我点击打印按钮时,windows的打印对话框窗口没有打开。我找不到问题所在,有人能帮我吗。 下面是我的代码:Javascript 如何打印字符串中的HTML数据,javascript,Javascript,我的项目中有一个打印按钮。我正在使用JavaScript打印数据。我有一个变量作为data_to_print,它包含要打印的HTML。问题是,当我点击打印按钮时,windows的打印对话框窗口没有打开。我找不到问题所在,有人能帮我吗。 下面是我的代码: function print_all() { var xx='<html> <head> <style>...</style> </head>
function print_all()
{
var xx='<html>
<head>
<style>...</style>
</head>
<body>
<center>
<div>
<table><thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Address</th>
<th>DOB</th>
</tr><thead>
<tr>
<td>1</td>
<td>John</td>
<td>Mumbai</td>
<td>15 August</td>
</tr>
<tr>
<td>2</td>
<td>John2</td>
<td>Mumbai2</td>
<td>18 August</td>
</tr>
</table>
</div>
</center>
</body>
<html>';
var content_vlue = xx;
content_vlue=content_vlue.replace("[Print]", "");
var docprint=window.open("","","");
docprint.document.open();
docprint.document.write('<html><head>');
docprint.document.write('<style> .table{border-collapse:collapse;}.table tr
th{border:1px solid #000!important;color:#000;}.table tr th
a{color:#000!important;}.table tr td{border:1px solid #000!important;}</style>');
docprint.document.write('</head><body><center>');
docprint.document.write('<div align="left">');
docprint.document.write(content_vlue);
docprint.document.write('</div>');
docprint.document.write('</center></body></html>');
docprint.document.close();
docprint.focus();
}
function print_all()
{
var xx='1
...
身份证件
名称
地址
出生日期
1.
约翰
孟买
8月15日
2.
约翰2
蒙拜2
8月18日
';
var含量=xx;
content\u vlue=content\u vlue.replace(“[打印]”,”);
var docprint=window.open(“,”,“);
docprint.document.open();
docprint.document.write(“”);
docprint.document.write('.table{border collapse:collapse;}.table tr
th{边框:1px实心#000!重要;颜色:#000;}。表格tr th
a{color:#000!重要;}。表trtd{border:1px solid#000!重要;}');
docprint.document.write(“”);
docprint.document.write(“”);
docprint.document.write(内容);
docprint.document.write(“”);
docprint.document.write(“”);
docprint.document.close();
docprint.focus();
}
您遇到麻烦的原因很简单。您忘记添加方法.print()代码>
当我理解你的权利时,请执行以下操作:
function print_all()
{
...
docprint.document.close();
docprint.focus();
//This line was missing
doc.print();
}
另外两个建议:
第一:
正如steo所写的,如果您想用Javascript打印长字符串,请使用加号将其压缩。浏览器不接受字符串中的换行符
第二:
当我使用链接的定义时
你检查错误控制台了吗?打印按钮中的代码是什么?@EvanKnowles我正在调用函数print\u all。这是我的代码@reporter控制台中没有任何错误。当我点击“打印”时,所有数据都会在浏览器的下一个选项卡中打开,但windows“打印”对话框不会打开。@Mukesh我想我找到了原因。看看我的答案。谢谢你的回答和建议,这对我很有效,这真的是一个愚蠢的错误,但对我来说是一个很大的错误。