为何两个window.open弹窗脚本的参数均受第二个控制?如何修复?
问题原因
你遇到的问题核心是:window.open()的第二个参数是窗口标识名称,当两个函数使用同一个名称(比如你代码里的popUpWindow)时,浏览器会复用这个已打开的窗口,新的窗口参数就会覆盖旧的设置。
解决步骤
只需做以下关键修改即可:
1. 给每个弹窗函数设置唯一的窗口名称
把两个window.open()的第二个参数改成不同的值,确保浏览器不会复用同一个窗口,比如第一个用firstPopupWin,第二个用secondPopupWin。
2. 修正函数调用的匹配错误
你第一个脚本定义的函数是firstPopup,但链接里却调用了newPopup,要把链接里的函数名改成对应脚本的函数名。
3. 修复HTML标签闭合问题
原始HTML里的<a>标签未正确闭合,会导致页面结构异常,需要补充闭合标签。
修改后的完整代码
<!-- 第一个弹窗脚本 --> <script> function firstPopup(url) { popupWindow = window.open(url, 'firstPopupWin', 'height=300,width=300,left=200,top=200,resizable=yes,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=yes'); } </script> <a href="JavaScript:firstPopup('bitcoin.cfm')" style="color:black">Here.</a> <a href="JavaScript:firstPopup('contactpri.cfm')" style="color:black">Another Link</a> 此处为其他文本内容。 <!-- 第二个弹窗脚本 --> <script> function newPopup(url) { popupWindow = window.open(url, 'secondPopupWin', 'height=700,width=800,left=10,top=10,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=yes'); } </script> <B>If you want to Contact US <a href="JavaScript:newPopup('contact.cfm')" style="color:#062689;">click here.</a></B>
额外优化建议
- 给
popupWindow变量添加let声明,避免全局变量污染:let popupWindow = window.open(...) - 尽量避免在
href里写JavaScript:伪协议,改用事件绑定方式更规范,示例:
<a href="bitcoin.cfm" class="first-popup-link" style="color:black">Here.</a> <script> document.querySelectorAll('.first-popup-link').forEach(link => { link.addEventListener('click', function(e) { e.preventDefault(); window.open(this.href, 'firstPopupWin', 'height=300,width=300,left=200,top=200,resizable=yes,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=yes'); }); }); </script>
内容的提问来源于stack exchange,提问作者MikeLieberman
相关产品推荐
相关产品推荐

