【问题标题】:Event listeners are not working on popup window when close it's parent window关闭它的父窗口时,事件侦听器不在弹出窗口上工作
【发布时间】: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>

【问题讨论】:

标签: javascript html popup window


【解决方案1】:

不要使用addEventListener,而是使用onclick 属性,以便它是持久的。

演示:https://codepen.io/craigiswayne/pen/moYYga

function myFunction() {
  var myWindow = window.open("", "_blank", "width=500,height=500");
  myWindow.document.write("<p>A new window!</p>");

  var printButton = myWindow.document.createElement('BUTTON');
  printButton.innerHTML = "PRINT";
  printButton.setAttribute("onclick", "window.print()");
  myWindow.document.body.appendChild(printButton);
}
<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>

您的方法不起作用的原因是,一旦父项更改,就没有对原始事件处理程序的引用。

由于运行代码的 iframe 的沙盒环境,上述代码无法在 StackOverflow 上运行。所以我添加了codepen链接来演示解决方案

【讨论】:

  • 嘿,如果我不想在打印页面上包含那个打印按钮怎么办?似乎上面的代码不适用于那种情况!
  • 当我点击打印按钮时,它会显示一个打印窗口,上面有一个打印按钮,所以我不希望页面上的打印按钮(在打印页面上)
  • 所以你只想要一个没有按钮的新窗口?我建议创建一个新问题,描述你问克里希纳的内容
  • 我想要这样:btn.addEventListener('click', () => { btn.style.display = 'none'; windowPopup.window.print(); btn.style.display = '块'; });
  • 这可以使用像 btn.addEventListener('click', () => { btn.style.display = 'none'; windowPopup.window.print(); btn.style 这样的事件监听器。显示 = '块'; });应该如何通过你的代码来实现这一点?
猜你喜欢
  • 2011-10-27
  • 1970-01-01
  • 2011-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-09
相关资源
最近更新 更多