繁体   English   中英

单击“打印”按钮时,不会打印“选择”选项中的值

[英]Values from Select option are not printed when I click on Print button

我编写了一个 javascript 按钮来打印我页面中的所有 HTML。 当我点击它时,除了选择option的值外,所有打印都很好。 下面是代码片段。

问题的现场演示:

https://codepen.io/T9-T9/pen/VwLKbOv

因此,在演示中,如果您将选项从“a”更新为“b”或其他并单击“打印结果”,它仍将打印默认的“a”而不是您选择的内容。 代码片段如下。

HTML:

<div class="container" id="printcontent">
        <div class="row">
            <div>
            <h4>Title here</h4>
                <form>
                    <fieldset>
                        <label class='life_area'>01</label>
                        <select id='01'>
                          <option value="1">a</option>
                          <option value="2">b</option>
                          <option value="3">c</option>
                          <option value="4">d</option>
                        </select>
                        <label class='life_area'>02</label>
                        <select id='02'>
                          <option value="1">a</option>
                          <option value="2">b</option>
                          <option value="3">c</option>
                          <option value="4">d</option>
                        </select>
                    </fieldset> 
                </form>         
            </div>
        </div>
    </div>
    <div id="print-content">
         <form>
          <input type="button" class="print-result" onClick="PrintElem('print-content')" value="print result"/>
        </form>
    </div>

JavaScript:

function PrintElem(elem)
        {
            var mywindow = window.open('', 'PRINT', 'height=800,width=2200');

            mywindow.document.write('<html><head>');
            mywindow.document.write('</head><body>');
            mywindow.document.write(document.getElementById('printcontent').innerHTML);
            mywindow.document.write('</body></html>');

            mywindow.document.close(); 
            mywindow.focus();       

            setTimeout(function () {
            mywindow.print();
            mywindow.close();
            }, 1000)
            return true;
        }

我进行了多次更新,但无法修复此部分。

元素的innerHTML只会检索HTML 标记——它不会检索可能不在HTML 中的元素的状态。 For example, when a select changes, that doesn't change the HTML markup. (同样,既不会将文本放入输入框中,也不会添加事件侦听器)。

在这种情况下,您可以遍历选择的选项,并为它们提供selected属性,该属性将反映在 HTML 标记中(因此可以正确检索)。 selected属性将导致在页面加载时选择相关选项:

for (const option of document.querySelectorAll('option:checked')) {
  option.setAttribute('selected', '')
}
mywindow.document.write(document.getElementById('printcontent').innerHTML);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM