window.open在IE7-8-9b中抛出无效参数

mar*_*dge 13 javascript internet-explorer javascript-events

我不太了解javascript来弄清楚为什么这个脚本中以"window.open ..."开头的行在IE7-8-9b中抛出了无效的参数错误.在Firefox和Webkit中运行良好.

(该脚本onclick="share.fb()"使用html链接进行调用,并弹出一个新的浏览器窗口以在FB和Twitter上共享).

var share = {
    fb:function(title,url) {
    this.share('http://www.facebook.com/sharer.php?u=##URL##&t=##TITLE##',title,url);
    },
    tw:function(title,url) {
    this.share('http://twitter.com/home?status=##URL##+##TITLE##',title,url);
    },
    share:function(tpl,title,url) {
    if(!url) url = encodeURIComponent(window.location);
    if(!title) title = encodeURIComponent(document.title);

    tpl = tpl.replace("##URL##",url);
    tpl = tpl.replace("##TITLE##",title);

    window.open(tpl,"sharewindow"+tpl.substr(6,15),"width=640,height=480");
    }
    };
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 33

IE不允许窗口名称中的空格和其他特殊字符(第二个参数).您需要在作为参数传递之前删除它们.

更换

"sharewindow"+tpl.substr(6,15)
Run Code Online (Sandbox Code Playgroud)

通过

"sharewindow"+tpl.substr(6,15).replace(/\W*/g, '')
Run Code Online (Sandbox Code Playgroud)

所以你最终得到了

window.open(tpl,"sharewindow"+tpl.substr(6,15).replace(/\W*/g, ''),"width=640,height=480");
Run Code Online (Sandbox Code Playgroud)

(这基本上是一个正则表达式的替代品,上面写着"无所谓地替换每个非语言字符序列")

这里的现场演示(必要时配置你的弹出窗口拦截器)