打印命令执行后Dropdown <option>重置,如何保留选中状态?
解决打印时下拉框选中状态重置的问题
问题核心在于直接获取元素的innerHTML时,select的当前选中状态不会被包含——innerHTML仅保留初始HTML结构,不会记录用户交互后的选中状态。要解决这个问题,需要先将当前选中的option的selected属性显式设置好,再获取HTML内容。
修改你的JavaScript代码如下:
function printdiv(printpage) { var printElement = document.getElementById(printpage); // 处理所有select的选中状态 var selects = printElement.querySelectorAll('select'); selects.forEach(select => { // 移除所有option的selected属性 Array.from(select.options).forEach(opt => opt.removeAttribute('selected')); // 给当前选中的option添加selected属性 select.options[select.selectedIndex].setAttribute('selected', 'selected'); }); var headstr = "<html><head><title></title></head><body>"; var footstr = "</body>"; var newstr = printElement.innerHTML; var oldstr = document.body.innerHTML; document.body.innerHTML = headstr + newstr + footstr; window.print(); document.body.innerHTML = oldstr; return false; }
另外建议把document.all.item(printpage)替换为标准的document.getElementById(printpage),后者兼容性更好,是更规范的DOM操作方式。
修改后,在获取打印内容前,会将用户选中的option的selected属性写入HTML结构,打印页面就能正确保留下拉框的选中状态了。
内容的提问来源于stack exchange,提问作者Cosmochen
相关产品推荐
相关产品推荐

