首页 > 解决方案 > 具体如何打印

使用 javascript 或 jquery 在新窗口中显示内容?

问题描述

我有一个简单的 html 代码,我使用了 javascript。(如果可以使用 jquery 建议我)

<script>
var myWindow;

function openWin() {
    myWindow = window.open("", "myWindow", "width=200,height=100");
    myWindow.document.write(#tobePrint);
}

function closeWin() {
    myWindow.close();
}
</script>
<!DOCTYPE html>
<html>
<body>
<div id="tobePrint">Print the content of this div content in new window.</div>

<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>
</body>
</html>

我正在尝试的新窗口出现在新选项卡中,我需要新窗口穿过选项卡的一侧。div 内的内容应该显示在那个新窗口中。所以我尝试了 myWindow.document。写(#tobePrint);访问 ID 并尝试打印,但它不工作。

标签: javascriptjqueryhtml

解决方案


这是工作解决方案:

var myWindow;

function openWin() {

    myWindow = window.open("myWindow","newwin") 
    var tobePrint = $('#tobePrint').text();
    myWindow.document.write('<p>' + tobePrint+ '</p>');
    
}

function closeWin() {
    myWindow.close();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div id="tobePrint">Print the content of this div content in new window.</div>

<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>
</body>


推荐阅读