如何在加载页面时打印子窗口的内容?

时间:2018-05-21 08:47:39

标签: javascript jquery

我有以下功能打开子窗口并使用AJAX填充一些内容。

function Print(){
jQuery.ajax({
    type: 'POST',
    data: {  
        //some fields
    },      
    url: 'getPageForPrint.php',
    success: function(data){
        var WinPrint = window.open('','','left=0,top=0,width=' + screen.width + 'px,height=' + screen.height + 'px,toolbar=0,scrollbars=1,status=0');
        WinPrint.document.write('<div style="background-color: #f8f8f8;">');
        WinPrint.document.write(data);
        WinPrint.document.write('</div>');

        var intervals = setInterval(function(){
            if($(WinPrint.document).find('#print_content').length > 0){
                WinPrint.document.close();
                WinPrint.focus();
                WinPrint.print();
                WinPrint.close();
                clearInterval(intervals);
            }
        }, 1000);
    }
});

}

问题是打印对话框在页面加载之前打开。

我试图插入此代码:

WinPrint.addEventListener('load', function(){
    console.log("Loaded!");
    if($(WinPrint.document).find('#print_content').length > 0){
        WinPrint.document.close();
        WinPrint.focus();
        WinPrint.print();
        WinPrint.close();
    }

}, false);

但它不起作用。

1 个答案:

答案 0 :(得分:0)

尝试使用jQuery用于确保在执行函数之前完全加载DOM的.ready方法: $(document).ready(function)

将您的函数粘贴到.ready()中只会在DOM完全呈现后运行该函数。