JavaScript在表单页面添加打印功能,打印表单中的值并打印完成后不刷新页面

在一个项目中,有一个功能需求

在一个页面上,有一个表单,表单包括textbox, radiobutton, checkbox, textarea等控件

用户填写表单后,按下submit按钮提交表单

现在用户有个需求,他们希望在这个页面上增加一个print按钮或者链接

点击print时,可以打印

 

最简单的想法就是,加上一个print的链接,然后调用javascript中的window.print()能打印

我最初是这样写代码的

在网页上增加一个print的链接

<a href="javascript:void(0)" onclick="printProduct()"><i class="fa fa-print" aria-hidden="true"></i>Print this page</a>

或者,也可以写成这样

<a href="javascript:printProduct()"><i class="fa fa-print" aria-hidden="true"></i>Print this page</a>

 然后,javascript的printProduct方法写成如下

function printProduct()
{
    document.body.innerHTML = document.getElementById("printDiv").innerHTML;
    window.print();
    history.go(0);
}

页面上,需要打印的表单写在id=printDiv的div中

实现这个功能后,发现几个问题

1.在页面填写好表单内容后,点击打印按钮时,打印出来的表单内容是空的,没有任何内容

2. 打印完成后,回到网页上,刚才网页上填写的内容,也全部都消失了

为什么会出现这种情况呢,怎么解决呢?

 产生这个问题的原因是

$("#form").html()时,没有包含你在网页上填写的数据。 为了解决这个问题,你需要用html()之前,把你在网页上填入表单的所有数据都val('')先

也就是说,在调用window.print()之前,我们需要一个javascript来bindData

这里,我写了一个bindData的javascript函数

function bindData()
{
    $("input[type='text'],select option").each(function () {
        $(this).attr('value', $(this).val());
    });

    $("input[type='radio'],input[type='checkbox']").each(function () {

        if ($(this).attr('checked'))
            $(this).attr('checked', true);
        else
            $(this).removeAttr('checked');

    });

    $("select option").each(function () {

        if ($(this).attr('selected'))
            $(this).attr('selected', true);
        else
            $(this).removeAttr('selected');
    });

    $('textarea').each(function () {
        $(this).html($(this).val());
    });


}

这样,把这个javascript函数放在打印之前。上面发生的第1个问题就解决了

我们在看第2个问题,点击打印按钮后,回到网页,发现网页上,你之前填写的内容都没有了

为了解决这个问题,我们采用另一种方式

我们在Javascript代码中,临时创建一个window窗口,然后把你要打印的内容写入这个临时的window窗口,打印完成后,再关闭这个新创建的窗口

代码如下

function printProduct()
{
    bindData();

    var printContent = document.getElementById("printDiv").innerHTML;
    var newWindow = window.open();
    newWindow.document.write(printContent);
    newWindow.print();
    newWindow.close();

   
}

到这里,整个网页表单打印功能就完成了

posted on 2020-01-10 11:53  新西兰程序员  阅读(1748)  评论(0编辑  收藏  举报