更好的方法来写这个弹出函数

Better way to write this popup function?

本文关键字:函数 方法 更好      更新时间:2023-09-26
function popUp(URL) {
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(URL, '" + id + "', 
       'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=400,height=600,left=600,top=300');");
}
<a href="javascript:popUp('http://google.com')">Open the Popup Window</a>

这是我现在的代码。我想改变它,以便它针对一个特定的类,如"弹出"和所有与该类的链接生成一个弹出窗口与链接在href .

就像这样:

<a class="popup" href="http://google.com">Open the Popup Window</a>

我该如何做到这一点?

最好的优化是删除它,让访问者决定是否要在新窗口中打开链接。至少,将代码移动到侦听器:

<a href="http://google.com" onclick="return popUp(this.href);">Open the Popup Window</a>

然后在弹出函数中,如果函数正确执行,则返回false。

 function popUp(URL){
day = new Date();
    id = day.getTime();
      window.open(URL,'"+id+"','toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=400,height=600,left=600,top=300');
 }

很抱歉来晚了,但这是我的两分钱:

用jquery做你的例子

<a class="popup" href="http://google.com">Open the Popup Window</a>

你可以使用:

var page = [], id=0;
$('.popup').click(function(e){
    e.preventDefault();
 // add to array of open popups
page.push(window.open(this.href,"page"+id,'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=400,height=600,left=600,top=300')); 
     id++;
    return false;
});

然后你可以使用类似这样的命令来关闭弹出窗口。

$('button').click(function(e){
   page.reverse();
   page.pop().close(); 
   page.reverse();
});