使用Jquery在新窗口中打开链接

使用Jquery在新窗口中打开链接

问题描述:

我正在尝试使用Jquery而不是_blank在新窗口中打开一些链接,因此我的html仍然有效.我的代码如下:

I am trying to open a few links in a new window using Jquery rather than _blank so my html remains valid. My code looks like this:

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

这很好用,除非链接包含在我使用Jquery load()方法放置在页面上的html中.谁能解释原因,请提供解决方案?

This works just fine except when the link is contained within html I have placed on the page using the Jquery load() method. Can anyone explain why and please help with a solution?

更新:如果您是在HTML5 +世界中阅读此书,请不再丢失,更准确地说)作为

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.

这将起作用:

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

但是,ID应该是唯一的,如果您加载的ID大于1,则它们需要具有一个类,如下所示:

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>

像这样的jQuery:

And jQuery like this:

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

符合标准的方式将是:

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