Open all links in new tabs with jQuery

2019-02-16 14:46发布

问题:

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/

回答1:

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;
});


回答2:

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!



回答3:

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>


回答4:

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



回答5:

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?