使用Jquery打印div内容 [英] Print a div content using Jquery

查看:932
本文介绍了使用Jquery打印div内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用jQuery打印div的内容。此问题已在SO中提出,但我无法找到正确的答案。



这是我的HTML:

 < div id ='printarea'> 
< p>这是用于打印目的的示例文本。< / p>
< input type ='button'id ='btn'value ='打印'>
< / div>
< p>请勿打印。< / p>

这里我想打印div printarea



我试过这个:

  $(#btn) .click(function(){
$(#printarea)。print();
});

但是,当点击按钮时会出现控制台错误:


Uncaught TypeError:$(...)。print不是函数

但是,当我试图打印整个页面使用

  window.print(); 

它正在工作。但我只想打印特定div的内容。我在很多地方看到了 $(#printarea)。print(); 的解答,但这是行不通的。 =h2_lin>解决方案

一些jQuery研究失败了,所以我转向了JavaScript(感谢您的建议 Anders )。



它运行良好...



HTML

 < div id ='DivIdToPrint'> 
< p>这是用于打印目的的示例文本。< / p>
< / div>
< p>请勿打印。< / p>
< input type ='button'id ='btn'value ='打印'onclick ='printDiv();'>

JavaScript

  function printDiv()
{

var divToPrint = document.getElementById('DivIdToPrint');

var newWin = window.open('','Print-Window');

newWin.document.open();

newWin.document.write('< html>< body onload =window.print()>'+ divToPrint.innerHTML +'< / body>< / html>' );

newWin.document.close();

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

}


I want to print the content of a div using jQuery. This question is already asked in SO, but I can't find the correct (working) answer.

This is is my HTML:

<div id='printarea'>
    <p>This is a sample text for printing purpose.</p>
    <input type='button' id='btn' value='Print'>
</div>
<p>Do not print.</p>

Here I want to print the content of the div printarea.

I tried this:

$("#btn").click(function () {
    $("#printarea").print();
});

But it gives a console error when the button is clicked:

Uncaught TypeError: $(...).print is not a function

But when I am trying to print the entire page using

window.print();

it is working. But I only want to print the content of a particular div. I saw the answer $("#printarea").print(); in many places , but this is not working.

解决方案

Some jQuery research has failed, so I moved to JavaScript (thanks for your suggestion Anders).

And it is working well...

HTML

<div id='DivIdToPrint'>
    <p>This is a sample text for printing purpose.</p>
</div>
<p>Do not print.</p>
<input type='button' id='btn' value='Print' onclick='printDiv();'>

JavaScript

function printDiv() 
{

  var divToPrint=document.getElementById('DivIdToPrint');

  var newWin=window.open('','Print-Window');

  newWin.document.open();

  newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');

  newWin.document.close();

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

}

这篇关于使用Jquery打印div内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆