如何实现点击按钮通过window.open()弹窗并添加关闭按钮关闭弹窗
解决弹窗关闭按钮功能缺失问题
要让弹窗里的关闭按钮生效,核心是给新窗口内的按钮绑定点击事件——因为弹窗是独立的窗口对象,原页面的事件绑定无法直接作用于它。以下是修改后的完整代码:
修改后的JavaScript代码
document.getElementById("mybtn").addEventListener("click", function() { var newWindowContent = document.getElementById("myContent").innerHTML; var newWindow = window.open("", "", "width=500,height=400"); newWindow.document.write(newWindowContent); // 监听新窗口的DOM加载完成事件,确保能获取到关闭按钮 newWindow.document.addEventListener('DOMContentLoaded', function() { // 获取新窗口里的close按钮,绑定关闭事件 newWindow.document.getElementById("mybtnn").addEventListener('click', function() { newWindow.close(); }); }); });
对应的HTML代码(无需改动,仅作参考)
<article type="text" id="editor" contenteditable="true"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatum ad eos, facere ipsam odio dignissimos voluptatibus dolor sunt qui ipsum, quos praesentium doloribus nulla mollitia laboriosam expedita maxime, asperiores consequuntur? </article> <h1>Open the element content when click the button</h1> <div id="myContent"> <button id="mybtnn">close</button> This is the content that will be inside the new popup window </div> <button id="mybtn">open</button>
关键说明
- 必须等待新窗口的
DOMContentLoaded事件触发后再获取按钮,否则新窗口的DOM还未渲染完成,会找不到mybtnn元素 - 调用
newWindow.close()可以直接关闭目标弹窗,也可以在新窗口的事件回调里用window.close()(因为此时的window指向新窗口本身)
内容的提问来源于stack exchange,提问作者Aakash Mishra
相关产品推荐
相关产品推荐

