最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - window.open in a function replaces current tab as well as opens new tab - Stack Overflow

programmeradmin6浏览0评论

I have a funny plication i would like to understand, if i have window.open as the onclick event of an anchor, a new tab is opened as required. If the onclick calls a function, which in turn does a window.open a new tab is opened, but also the current tab gets the new url as well.

I can demonstrate it here it works ok when you click on the link, wheras here the url is also opened in the results area as well !

Thanks Symeon.

I have a funny plication i would like to understand, if i have window.open as the onclick event of an anchor, a new tab is opened as required. If the onclick calls a function, which in turn does a window.open a new tab is opened, but also the current tab gets the new url as well.

I can demonstrate it here it works ok when you click on the link, wheras here the url is also opened in the results area as well !

Thanks Symeon.

Share Improve this question asked Apr 18, 2012 at 15:41 Symeon BreenSymeon Breen 1,54111 silver badges25 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

Your first case statement is falling through. You need to add a break:

switch (t) {
    case 1: 
        window.open(url,"_blank");
        break;
    case 2: 
        window.location = url;
        break;
}

Without the break, every case below the one that was first matched will be executed.

I have added a break to the second case too, simply because it's generally considered good practice to always break a case. In fact, JSLint will flag a missing break as an error.

In the example that isn't working, you are missing a break in the switch statement:

function doclick(t, url) {
    switch (t) {
        case 1: window.open(url,"_blank"); break;
        case 2: window.location = url; break;
    }
    return false;
}​

You need to break; your cases.

only break; will give you your required results.

发布评论

评论列表(0)

  1. 暂无评论