微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用jquery自动打印

我有以下格式的数据:

(虚拟条目)(id = posGridView)

当我处理销售时,一张小收据会自动打印所选列,而不是所有列.

由于此网格视图中的所有数据都可用,如何使用jquery以任何格式动态打印它?

编辑

实际上我想从上面的网格视图中动态打印这种格式

解决方法

印花

打印页面不需要jQuery,只需要JavaScript函数:window.print();.

如果需要打印特定内容,可以通过CSS隐藏其余内容(并格式化打印区域):

<style media="screen">
  .noprint{ display: block; }
  .yesPrint{ display: block !important; }
</style> 
<style media="print">
  .noprint{ display: none; }
  .yesPrint{ display: block !important; }
</style>

如您所见,通过设置样式标记的media属性,您可以为普通视图(屏幕)和打印视图(打印)设置样式.全文是here.

力度

您可以为流程添加一定的动态,但请记住,它可以为用户提供动态,但在您的代码中,您必须找到并附加打印事件.该事件可能是锚点击:

< a href ='javascript:window.print();'>打印< / a>

它可能是您网页的onload事件:

window.onload = function () {
    window.print();
}

或者您可能需要注意的任何其他事件(请注意,现在我正在使用jQuery):

var doPrintPage;

function printPage(){
    window.print();
}

$(document).ready(function(){
    $('input').blur(function(){
        //3sec after the user leaves the input,printPage will fire
        doPrintPage = setTimeout('printPage();',3000);
    });
    $('input').focus(function(){
        //But if another input gains focus printPage won't fire
        clearTimeout(doPrintPage);
    });
});

上面的代码非常简单:在用户离开输入三秒后,printPage将会触发.如果输入在这三秒内获得焦点,则不会调用printPage.我真的不认为这个精确的代码是你需要的,但我会指出如何模仿动态.这里可以看到setTimeoutclearTimeout的定义.

编辑:我几乎不建议你通过CSS隐藏你不想要的打印html,如上所述,并调用window.print.无论如何,我在这里添加了一些代码,用于通过新页面进行操作.

从全新页面打印

如果你想从一个完全不同的页面打印你正在展示的页面,你可以要求该页面,管理服务器端的html,然后在加载后立即告诉页面打印.至少有两种方法可以做到这一点.让我们一步一步看到它们:

A)第一种选择是将GridView发送到新页面并从那里打印.问题是您无法轻松打开新页面来执行此操作,因此您必须从页面浏览到显示html-to-print的新页面.

A1)为此,您需要使用以下形式包围GridView:

<form runat="server">
<asp:GridView id="gridView" />
<asp:Button id="btnPrint" Text="Print" runat="server" OnClick="btnPrint_Click" />
</form>

A2)然后从* btnPrint_Click *你将调用你的“printPage.aspx”.请记住,如果您使用JS / jQuery更改了GridView,那些更改可能无法使用(因为.NET可能会读取隐藏的状态变量而不是GridView).

B)第二种方法是通过JavaScript.但请记住,如果您想在新页面中编辑表格,那么通过此选择将会很困难(因为您将不会收到GridView,您将收到html).好消息是您可以轻松打开新页面

B1)当然,你需要一个表格(注意其目标和行动),例如:

<form id="myPageForm" name="myPageForm" target="_blank" action="printPage.aspx">
    <input type="hidden" name="htmlToPrint" id="htmlToPrint" />
    <input type="button" value="submit">Print</button>
</form>

B2)然后你必须将你的数据传递给那个锚点.在提交表单之前,使用表数据设置输入:

$(document).ready(function(){
    $('#myPageForm').submit(function(){
        //Filling the hidden input
        var htmlToPrint = $(".posGridView").html(); //I'm using a class and not an ID 'cause .NET will change your GridView's ID when rendering you page
        $("#htmlToPrint").value(htmlToPrint);
        return true;
    });
});

一旦在服务器端获得了数据(printPage.asx),就可以轻松地创建HTML-to-print并在该页面onload上调用window.print(),如上所述.

原文地址:https://www.jb51.cc/jquery/178926.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐