![](/img/trans.png)
[英]How can get the refreshed option values from database only when i click on select box?
[英]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.