Javascript 如何获得<;选择>;打印前要更新的值?
我在打印值时发现了一件奇怪的事情Javascript 如何获得<;选择>;打印前要更新的值?,javascript,Javascript,我在打印值时发现了一件奇怪的事情 jQuery(document).ready(function(){ jQuery('#print_btn').on('click', function(){ var divToPrint=document.getElementById("print_tbl"); newWin= window.open(""); newWin.document.write(divToPrint.outerHTML); newWin.print
jQuery(document).ready(function(){
jQuery('#print_btn').on('click', function(){
var divToPrint=document.getElementById("print_tbl");
newWin= window.open("");
newWin.document.write(divToPrint.outerHTML);
newWin.print();
newWin.close();
});
});
如果单击“打印”,您将看到值为1。
如果将该值更改为2,然后再次单击“打印”,则该值仍然为1
如何获取打印图像以反映更改?虽然epascarello的评论是最好的方法,但您可以通过将
selected
属性添加到与其父级selectedIndex
成员相对应的选项来避开这种方法。完成后,正确的选项将显示在打印结果中
以下是一些能够实现这一目的的JS:
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
function allByTag(tagName,parent){return (parent == undefined ? document : parent).getElementsByTagName(tagName);}
function forEachNode(nodeList, func){for (var i=0, n=nodeList.length; i<n; i++) func(nodeList[i], i, nodeList); }
// **** below function updated in an EDIT ****
function setListSelectedAttrib(selectElem)
{
var selectedIndex = selectElem.selectedIndex;
var i, n = selectElem.options.length;
for (i=0;i<n;i++)
{
if (i == selectedIndex)
selectElem.options[i].setAttribute('selected', '');
else
selectElem.options[i].removeAttribute('selected');
}
}
function onPrintClicked(evt)
{
var elemToPrint = byId('print_tbl');
var selectElems = allByTag('select', elemToPrint);
forEachNode(selectElems, eachSelElemFunc);
function eachSelElemFunc(curElem, indexOfCurElem, listOfElems)
{
setListSelectedAttrib(curElem);
}
var newWin = window.open();
newWin.document.write(elemToPrint.outerHTML);
newWin.print();
newWin.close();
}
函数byId(id,parent){return(parent==未定义?文档:parent).getElementById(id);}
函数allByTag(标记名,父项){返回(父项==未定义?文档:父项).getElementsByTagName(标记名);}
函数forEachNode(nodeList,func){for(var i=0,n=nodeList.length;i您可以尝试使用css媒体查询而不是javascript来确定打印内容
@media print {
* {
visibility : hidden;
}
.print {
visibility : visible;
}
}
请注意,在提供的示例中,只有World将在FIDLE中打印问题在于您只是将HTML推送到打印窗口。不幸的是,
元素在内部存储其selectedIndex,并且在更改时不会更新HTML。一种方法是构建一些表示lis的HTMLt它确实选择了一个特定的项目,即-正确的选项具有selected
属性。您可以逐个选择选项,如果未选择,则输出它们的outerHTML,如果未选择,则输出一些稍有不同的html。
元素的.selectedIndex
成员可以告诉您它在单个html中e-selection list.CSS打印介质,无需打开窗口设置内容。感谢您的代码。它几乎可以工作。当它将所选标记添加到新选项时,它似乎会将所选标记留在后面。因此它只允许您更改一次选择。@LeeLoftiss-修复简单。在setListSelectedAttrib函数中,只需单步执行opt离子元素一个接一个。如果是选定的元素,请执行我正在执行的操作。如果不是,请调用.RemoveAttribute('selected')。我已更新了解决方案和fiddle链接。:)