登录
首页 >  文章 >  前端

使用 JavaScript 打印表单时,如何获取表单元素的真实值?

时间:2024-11-20 19:09:47 198浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《使用 JavaScript 打印表单时,如何获取表单元素的真实值? 》,正文内容主要涉及到等等,如果你正在学习文章,或者是对文章有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!

使用 JavaScript 打印表单时,如何获取表单元素的真实值?

在使用 JavaScript 打印表单时,可能会遇到修改后某些表单元素不起效的情况,如 textarea 内容无法显示或复选框不呈现选中状态。

原因是获取元素内容时使用的是 outerHTML,该方法会返回元素及其子元素的 HTML 标记代码,但其中不包含表单元素的实际值。

修改方法如下:

使用 cloneNode 方法克隆原表单元素,该方法能复制元素及其内容的副本,从而获取表单元素的真实值。

修改后的代码:

let docHtml1 = ''
docHtml1 += $('#divKanZhengPanel-binli').cloneNode(true).prop('outerHTML');

完整代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.js"></script>
</head>
<body>
<div id="divKanZhengPanel-binli">
    <div>
        &lt;input type=&quot;text&quot;&gt;
        &lt;textarea name=&quot;&quot; id=&quot;&quot; cols=&quot;30&quot; rows=&quot;10&quot;&gt;&lt;/textarea&gt;
        <div class="checkDiv">
            &lt;input autocomplete=&quot;off&quot; class=&quot;inputs&quot; type=&quot;checkbox&quot; name=&quot;yangwei&quot; value=&quot;正位&quot;&gt;<label>正位</label>
            &lt;input autocomplete=&quot;off&quot; class=&quot;inputs&quot; type=&quot;checkbox&quot; name=&quot;yangwei&quot; value=&quot;外显斜&quot;&gt;<label>外显斜</label>
            &lt;input autocomplete=&quot;off&quot; class=&quot;inputs&quot; type=&quot;checkbox&quot; name=&quot;yangwei&quot; value=&quot;内显斜&quot;&gt;<label>内显斜</label>
            &lt;input autocomplete=&quot;off&quot; class=&quot;inputs&quot; type=&quot;checkbox&quot; name=&quot;yangwei&quot; value=&quot;外隐斜&quot;&gt;<label>外隐斜</label>
            &lt;input autocomplete=&quot;off&quot; class=&quot;inputs&quot; type=&quot;checkbox&quot; name=&quot;yangwei&quot; value=&quot;内隐斜&quot;&gt;<label>内隐斜</label>
        </div>
    </div>
</div>
<button id="dw">点我打印</button>
<script>
    document.getElementById('dw').addEventListener('click', function () {
        $('#print-iframe').remove(); // 每次打印前移除先前生成的元素
        // 开始打印
        let iframe1 = document.createElement('IFRAME');
        let doc1 = null;
        iframe1.setAttribute('id', 'print-iframe');
        iframe1.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-0px;top:-0px;visibility: auto;');
        document.body.appendChild(iframe1);
        setTimeout(function () {
            doc1 = iframe1.contentWindow.document;
            doc1.body.appendChild(document.querySelector('#divKanZhengPanel-binli').cloneNode(true));
            doc1.close();
            iframe1.contentWindow.focus();
            iframe1.contentWindow.print();
        });
    });

</script>
</body>
</html>

好了,本文到此结束,带大家了解了《使用 JavaScript 打印表单时,如何获取表单元素的真实值? 》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多文章知识!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>