Open all links in new tabs with jQuery

我只是一个虾纸丫 提交于 2019-12-01 03:14:38

You could do this (which lets the users browser decide whether to open a new window or tab)

$('a').live('click', function() {
    window.open($(this).attr('href'));
    return false;
});

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 your tweet 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:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>

<body>


<a href="http://www.google.com">test</a>
<br />
<a href="http://www.yahoo.com">test2</a>

<script>
    $('a').attr('target', '_blank');
</script>

</body>

</html>

It's not working because the <a> is not yet part of your page when $('a').attr("target","_blank"); is fired.

GGCO

Try:

$('a').attr({ target: "_blank" });

Also, try "_new" instead of blank. If that doesn't work, why not post the generated html or your entire javascript code?

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