【发布时间】:2019-03-23 06:12:11
【问题描述】:
我想让我的打印按钮在弹出窗口上工作,但问题是当我关闭父窗口或在父窗口中的另一个 URL 上导航时,我的弹出窗口中的打印按钮不起作用。
事件侦听器在弹出窗口中不起作用可能是它们随着父窗口消失。
注意:当父窗口存在时它工作正常
下面是我正在使用的代码,请帮助我
<!DOCTYPE html>
<html>
<body>
<p>Click the button to open a new window, and assure that the new window GETS focus (send the new window to the front).</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var myWindow = window.open("", "_blank", "width=200,height=100");
myWindow.document.write("<p>A new window!</p>");
var printButton = myWindow.document.createElement('BUTTON');
var buttonNode = myWindow.document.createTextNode('PRINT');
printButton.appendChild(buttonNode);
myWindow.document.body.insertAdjacentHTML('beforeend', printButton.outerHTML);
var btn = myWindow.document.querySelector('button');
btn.addEventListener('click', () => {
myWindow.window.print();
});
}
</script>
</body>
</html>
【问题讨论】:
-
stackoverflow.com/questions/32357312/…, stackoverflow.com/questions/29909927/…, OR jsfiddle.net/murx2o9p .. 不过我不喜欢我自己的解决方案。
-
在 Safari 中为我工作
-
@Jason 我也不喜欢你的解决方案.....但感谢您的回复
标签: javascript html popup window