问题描述
我正在尝试使用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 +世界中阅读此书,请不再使用target
属性(不再丢失,更准确地说)作为它在XHTML 1.0中(原始问题上下文).我建议如果您现在正在阅读此书,忽略下面的所有内容,使用target
属性,无论是否引发合规警告,所有浏览器都支持,并且永远不会应该被排除在外...在以后的规范中重新添加的事实表明删除它是一个错误.
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;
});
这篇关于使用Jquery在新窗口中打开链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!