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.

我想使用jQuery打印div的内容。这个问题已经提出来了,但是我找不到正确的答案。

This is is my HTML:

这是我的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.

这里我要打印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

未捕获TypeError:$(…)。打印不是函数

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.

它是有效的。但是我只想打印特定div的内容。我看到了答案$(“#printarea”).print();在很多地方,这是行不通的。

9 个解决方案

#1


36

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

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

And it is working well...

它运行得很好……

HTML

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

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

}

更多相关文章

  1. Nivoslider(在动态ajax内容中)不会在第一次加载时加载图像
  2. 使用javascript或jquery将具有相同id的多个文本区域内容复制到剪
  3. 在内容可编辑DIV中的选定文本周围包装bb代码
  4. AJAX内容更改加上小变化效果
  5. 获取html DOM元素内容的边框
  6. jquery 更改angularJS input 内容导致绑定失效的解决办法
  7. 如何使我的AJAX内容能够被谷歌抓取?
  8. python 核心编程第六章课后题自己做的答案
  9. python将回车作为输入内容

随机推荐

  1. MySQL如何实时同步数据到ES?试试这款阿里
  2. 肝了一周总结的SpringBoot实战教程,太实用
  3. DockerHub访问慢怎么破?自建个企业级镜像
  4. 干掉Navicat!MySQL官方客户端到底行不行?
  5. PMP考试个人感想
  6. Elasticsearch官方已支持SQL查询,用起来贼
  7. 解放双手!MyBatis官方代码生成工具给力!
  8. 还在使用第三方Docker插件?SpringBoot官方
  9. 当Swagger遇上YApi,瞬间高大上了!
  10. Lombok有啥牛皮的?SpringBoot和IDEA官方都