每个按钮单独弹出独立窗口问题求助(附JS代码)
问题分析与解决方案
嘿,这个问题我熟!你遇到的核心问题在于窗口名称的复用——你在window.open方法里把第二个参数(窗口的标识名称)写死成了固定的"popupWindow",浏览器的规则是:如果指定了相同名称的窗口,就会复用这个窗口而不是新建。所以不管你点哪个按钮,都会在同一个窗口里加载新内容。
修复后的代码
$(document).ready(function(){ // 注意这里要加 . ,因为是类选择器 $(".custom_button").on({ mousedown: function (event) { if( event.which <= 2 ) { var button_id = this.id, button_href_id = "#" + button_id + "-href"; event.preventDefault(); // 关键改动:用按钮的id生成唯一的窗口名称 window.open( $(button_href_id).attr("href"), "popupWindow_" + button_id, // 每个按钮对应唯一的窗口名 "width=1400,height=900,scrollbars=yes" ); } } }); });
关键改动说明
- 类选择器修正:原代码里的
$("custom_button")应该改成$(".custom_button"),因为你要选择的是拥有custom_button类的元素,类选择器需要以.开头,不然会被当成标签名查找。 - 动态窗口名称:把固定的
"popupWindow"改成"popupWindow_" + button_id,利用每个按钮唯一的id生成专属的窗口名称,这样浏览器就会为每个按钮创建独立的新窗口了。
如果你的按钮没有id,也可以用href属性的部分来生成唯一名称,比如:
var href = $(button_href_id).attr("href"); window.open(href, "popupWindow_" + href.replace(/[^a-zA-Z0-9]/g, "_"), "width=1400,height=900,scrollbars=yes");
这样即使没有id,也能保证窗口名称唯一。
内容的提问来源于stack exchange,提问作者Yiwei Jiang
相关产品推荐
相关产品推荐

