Open link in new window with Jquery

两盒软妹~` 提交于 2019-12-04 04:48:49

Update: If you're reading this in an HTML5+ world the target attribute is no longer deprecated (no longer missing, to be more accurate) as it was in XHTML 1.0 (the original question context). I suggest if you're reading this now, ignore everything below, use the target attribute whether it throws a compliance warning or not, all browsers support it and it never should have been left out...the fact it was added back in a later spec shows removing it was a mistake.


This will work:

$('a#external-url').live('click', function(){
  $(this).attr('target','_blank');
});

However, IDs should be unique, if you're loading more than 1, they need to have a class instead, like this:

<a href="http://google.com" class="exteral-url">Google</a>

And jQuery like this:

$('a.external-url').live('click', function(){
  $(this).attr('target','_blank');
});

The standards compliant way would be:

$('a.external-url').live('click', function(e){
  window.open(this.href);
  e.preventDefault(); //or return false;
});
$(function(){
    $('a[id="external-url"]').click(function(){
        window.open(this.href);
        return false;
    });
});

http://snipplr.com/view/4626/jquery-snip--open-link-in-new-window/

Use .live()

$('a[id="external-url"]').live("click", function(){
        $(this).attr('target','_blank');
    });

Your code will bind click event to elements that are available at the page load and not to dynamically created elements. Live will bind events to elements that are dynamically created also.

On the contrary what others believe, the target attribute with all its values are not deprecated as per HTML5 specification.

You can read it about here: http://dev.w3.org/html5/markup/a.html

The target attribute on the a element was deprecated in a previous version of HTML, but is no longer deprecated, as it useful in Web applications, particularly in combination with the iframe element.

So, feel free to use it in HTML5.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!