How can I open a link in a new window?

后端 未结 10 1046
不知归路
不知归路 2020-11-30 19:21

I have a click handler for a specific link, inside that I want to do something similar to the following:

window.location = url

I need this

相关标签:
10条回答
  • 2020-11-30 19:29

    I just found an interesting solution to this issue. I was creating spans which contain information based on the return from a web service. I thought about trying to put a link around the span so that if I clicked on it, the "a" would capture the click.

    But I was trying to capture the click with the span... so I thought why not do this when I created the span.

    var span = $('<span id="something" data-href="'+url+'" />');
    

    I then bound a click handler to the span which created a link based on the 'data-href' attribute:

    span.click(function(e) {
        e.stopPropagation();
        var href = $(this).attr('data-href');
        var link = $('<a href="http://' + href + '" />');
        link.attr('target', '_blank');
        window.open(link.attr('href'));
    });
    

    This successfully allowed me to click on a span and open a new window with a proper url.

    0 讨论(0)
  • 2020-11-30 19:29

    What's wrong with <a href="myurl.html" target="_blank">My Link</a>? No Javascript needed...

    0 讨论(0)
  • 2020-11-30 19:33

    You can like:

    window.open('url', 'window name', 'window settings')
    

    jQuery:

    $('a#link_id').click(function(){
      window.open('url', 'window name', 'window settings');
      return false;
    });
    

    You could also set the target to _blank actually.

    0 讨论(0)
  • 2020-11-30 19:34

    Microsoft IE does not support a name as second argument.

    window.open('url', 'window name', 'window settings');
    

    Problem is window name. This will work:

    window.open('url', '', 'window settings')
    

    Microsoft only allows the following arguments, If using that argument at all:

    • _blank
    • _media
    • _parent
    • _search
    • _self
    • _top

    Check this Microsoft site

    0 讨论(0)
  • 2020-11-30 19:35

    Be aware if you want to execute AJAX requests inside the event handler function for the click event. For some reason Chrome (and maybe other browsers) will not open a new tab/window.

    0 讨论(0)
  • 2020-11-30 19:41

    Here's how to force the target inside a click handler:

    $('a#link_id').click(function() {
        $(this).attr('target', '_blank');
    });
    
    0 讨论(0)
提交回复
热议问题