使用 jQuery 打开新选项卡中的所有链接
我有一些链接通过 JSON 动态放置在我的页面中,但无法直接编辑它们。我想强制所有链接在新选项卡中打开,ala target="_blank"
认为这会起作用..但遗憾的是事实并非如此。有什么想法吗?
$('a').attr("target","_blank");
这是带有动态代码的 jsFiddle: http://jsfiddle.net/danielredwood/mrgta/7/
I have some links that are placed in my page dynamically via JSON and have no way to directly edit them. I want to force all links to open in new tabs, ala target="_blank"
Thought this would work.. but sadly it isn't. Any ideas?
$('a').attr("target","_blank");
Here's a jsFiddle with the dynamic code:
http://jsfiddle.net/danielredwood/mrgta/7/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以这样做(让用户浏览器决定是否打开新窗口或选项卡) :
对于 jQuery 1.7+,
You could do this (which lets the users browser decide whether to open a new window or tab)
For jQuery 1.7+:
你的问题可能是时间问题。
请记住,当您调用诸如
$('a').attr(...whatever...)
之类的内容时,它将立即生效,无论何时以及页面上所有现有元素。因此,...如果您的tweet
插件是异步的,并且执行时间超过 0 毫秒,那么您的代码似乎正在尝试更改甚至不存在于页面尚未。也就是说,您可能 (A) 调用
tweet
插件,(B) 更改页面上的所有链接,然后 (C) 推文插件完成并在页面上注入一堆新链接之前被错过了。因此,您可以尝试的是查看您正在使用的
tweet
插件是否具有某种“全部完成”或其他完成回调,然后您可以使用它们来更改链接标记。或者,就像我也赞同的另一个建议的答案一样,不仅仅是尝试更改链接标签,而是监听(实时)页面上的任何链接点击,并在该时间点拦截它们。这样,您就无需担心 tweet 插件的计时/完成,因为您可以使用在任何时间点都有效的事件委托 (live
)。请参阅 Petah 的答案,了解如何执行此操作的一个很好的示例。祝你好运!
Your problem might be one of timing.
Keep in mind, when you call something like
$('a').attr(...whatever...)
, that it will take effect instantly, upon any and all existing elements on the page. So, ... if yourtweet
plugin is asynchronous and takes more than 0 milliseconds to perform, it looks like your code is trying to change attributes on links that don't even exist on the page yet.That is, you might be (A) calling the
tweet
plugin, (B) changing all links on the page, and then (C) the tweet plugin completes and injects a bunch of new links on the page that got missed earlier.So, what you could try, is see if the
tweet
plugin you are using has some kind of "all-done" or other completion callback, that you could then use to change around the link tags. Or, like another answer suggested, which I also endorse, is to not just try and change the link tags, but to instead listen (live) upon any link clicks on the page, and intercept them at that point in time. This way, you don't need to worry about the timing/completion of the tweet plugin, since you could use event delegation (live
) which works at any point in time. See the answer from Petah for a great example of how to do this.Good luck!
这对我有用:
This works for me:
尝试:
另外,尝试“_new”而不是空白。如果这不起作用,为什么不发布生成的 html 或整个 javascript 代码呢?
Try:
Also, try "_new" instead of blank. If that doesn't work, why not post the generated html or your entire javascript code?
它不起作用,因为当
$('a').attr("target","_blank");
为被解雇了。It's not working because the
<a>
is not yet part of your page when$('a').attr("target","_blank");
is fired.