如何使用javascript或jquery在新窗口中打印特定的<div>内容?

时间:2018-11-27 11:25:15

标签: javascript jquery html

我有一个使用javascript的简单html代码。(如果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 中的内容应显示在新标签页中window.so,所以我尝试 myWindow.document.write(#tobePrint); 访问ID并尝试打印,但是它不起作用。

3 个答案:

答案 0 :(得分:1)

这是有效的解决方案:

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>

答案 1 :(得分:0)

您可以从打开的窗口底部一行的类似代码中获取div内容

 window.opener.document.getElementById('tobePrint').innerHTML

答案 2 :(得分:0)

从子窗口中获取“ tobePrint” div的内容。将此代码写在您的子窗口上。

$(document).ready
(
   function () 
  {
      alert(window.parent.document.getElementById('tobePrint').innerHTML);
              }

  );