如何让菜单弹窗按钮的链接在当前标签页打开且弹窗正常显示?
解决当前标签页打开弹窗的问题
首先得搞清楚为什么你把_blank改成_self后弹窗没出现:window.open('_self')本质上就是让浏览器在当前窗口直接加载目标URL,相当于普通的页面跳转,完全没有"弹窗"的特性——原来的逻辑是打开新标签页/独立弹窗窗口,改成_self后就变成了跳转页面,自然看不到弹窗效果。
要实现点击按钮后在当前标签页弹出窗口(比如模态框),得换一种思路,不能再依赖window.open,而是用前端的模态框组件来实现。下面分两种常见场景给你解决方案:
场景1:目标URL是弹窗内容页面
如果<?php echo esc_url( $menu_btn_url ); ?>指向的是专门用来做弹窗内容的页面,你可以用AJAX把内容加载到当前页面的模态框里,步骤如下:
- 先在页面中添加一个隐藏的模态框容器(假设你用Bootstrap,因为按钮带
btn类,大概率用了Bootstrap):
<!-- 模态框容器 --> <div class="modal fade" id="menuModal" tabindex="-1" aria-labelledby="menuModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="menuModalLabel">弹窗标题</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body" id="modalContent"> <!-- AJAX加载的内容会放到这里 --> </div> </div> </div> </div>
- 修改按钮的
onclick事件,去掉window.open,改成触发AJAX加载并显示模态框:
<button class="btn btn-bg-no btn-border-green btn-color-green hvr hvr-buzz-out" onclick="openMenuModal()"> <?php echo esc_html( $menu_btn ); ?> </button> <script> function openMenuModal() { const modalContent = document.getElementById('modalContent'); const modal = new bootstrap.Modal(document.getElementById('menuModal')); // 用AJAX加载目标URL的内容 fetch('<?php echo esc_url( $menu_btn_url ); ?>') .then(response => response.text()) .then(html => { modalContent.innerHTML = html; modal.show(); // 显示模态框 }) .catch(error => { console.error('加载弹窗内容失败:', error); modalContent.innerHTML = '加载失败,请重试'; modal.show(); }); } </script>
场景2:目标URL是普通页面,要在当前页弹窗展示
如果目标页面是普通页面,不想跳转但要弹窗展示,可以用iframe嵌入到模态框里:
修改模态框的modal-body部分:
<div class="modal-body"> <iframe src="" id="modalIframe" width="100%" height="400px" frameborder="0"></iframe> </div>
然后修改JS函数:
function openMenuModal() { const iframe = document.getElementById('modalIframe'); const modal = new bootstrap.Modal(document.getElementById('menuModal')); iframe.src = '<?php echo esc_url( $menu_btn_url ); ?>'; modal.show(); }
额外注意事项
- 如果你没用Bootstrap,也可以用其他前端框架的模态框组件(比如Vue的Modal、React的Modal),或者自己写纯CSS+JS的模态框逻辑,核心思路都是在当前页面加载内容并弹出层展示,而不是跳转页面。
- 确保目标URL允许跨域请求(如果是同域名就没问题),否则AJAX会报错,这时候用iframe是更稳妥的选择。
内容的提问来源于stack exchange,提问作者Tatiana Kiryukhina
相关产品推荐
相关产品推荐

