zoukankan      html  css  js  c++  java
  • 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();
    
       
    }

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

  • 相关阅读:
    应用程序框架实战十三:DDD分层架构之我见
    Util应用程序框架公共操作类(三):数据类型转换公共操作类(扩展篇)
    Util应用程序框架公共操作类(二):数据类型转换公共操作类(源码篇)
    不能使用 float 和 double 来表示金额等精确的值
    JVM 字节码指令手册
    MyBatis: Invalid bound statement (not found)错误的可能原因
    Oracle:ORA-01219:database not open:queries allowed on fixed tables/views only
    手写 Spring MVC
    8080 端口被占用的解决方法 netstat -ano;taskkill (命令行)
    Java 工具类 IpUtil
  • 原文地址:https://www.cnblogs.com/wphl-27/p/12175456.html
Copyright © 2011-2022 走看看