2015-07-20 27 views
3

我在打印值時發現了一件奇怪的事情。如何在打印前獲得<select>值更新?

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(); 
}); 
}); 

Take a look at this fiddle

如果您單擊打印,你會看到值爲1 如果將值更改爲2,然後再次打打印,該值仍然是1

如何我可以獲得印刷圖像以反映變化嗎?

+0

問題是,你只能通過推HTML到打印窗口。不幸的是,''元素的'.selectedIndex'成員可以告訴你它在單選列表中。 – enhzflep

+1

CSS打印媒體,不需要打開窗口並設置內容。 – epascarello

回答

2

雖然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(); 
} 

在這裏看到一個小提琴:https://jsfiddle.net/jpkz0fyp/1/

+0

感謝您的代碼。這幾乎是作品。當它將它們添加到新的OPTION時,它似乎將SELECTED標籤留下。所以它只允許你改變一次SELECT。 –

+0

@LeeLoftiss - 簡單解決。在setListSelectedAttrib函數中,只需逐個瀏覽選項元素。如果它是所選的那個,那就做我已經在做的事情。如果不是,請調用.removeAtribute('selected')。我已經更新了我的解決方案和小提琴鏈接。 :) – enhzflep

-1

問題是您打印另一個窗口。這將打印當前窗口。

jQuery(document).ready(function(){ 
    jQuery('#print_btn').on('click', function() { 
     window.print(); 
    }); 
}); 
+0

這就是OP想要做的事情....用內容打印另一個窗口。 – epascarello

1

你可以嘗試使用CSS媒體查詢,而不是JavaScript來確定印什麼。您可以通過使用下面的代碼

@media print { 
    * { 
     visibility : hidden; 
    } 
    .print { 
     visibility : visible; 
    } 
} 
在所提供的例子只是 世界

http://jsfiddle.net/k2mtaob2/2/

公告將在小提琴打印上手