Target _blank in all Link

拥有回忆 提交于 2019-12-05 00:48:55

Put this in your <head>

<base target="_blank">

It will make all URLs on a page open in a new page, unless target is specified.

This is a HTML5-only feature, I learnt it from Google's io-2012-slides slide package.

Oliver Spryn

To answer your question, jQuery makes this easy:

<script src="//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script>
    $(function() {
        $('a[href]').attr('target', '_blank');
    });
</script>

This will not modify any <a> tags without an href attribute.

It's pretty simple in plain JS too:

var links = document.getElementsByTagName('a');
for (var i=0, len=links.length; i < len; i ++) {
  links[i].target = '_blank';
}

(Put this script right before your closing </body> tag or in any case after all the <a> tags on your page.)

If you are unable to do a simple find and replace using your HTML editor, you can do something like this using jQuery:

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

This will automatically do a target="_blank" for every a that is clicked and open in a new window or new tab(you have no control over this, it depends on user's browser settings).

FIDDLE

Hope this helps!!

I've had to deal with this lots of times. Just for the record:

I think there's no need to make javascript perform this task, but here's another approach, instead you can use the find/replace function of your editor and do something like this (provided your links are in that format):

  • Open your editor and look for <a href:

  • On the replace field type <atarget="_blank"href.

  • Replace.

Or you can append that to the end of the tag by looking for .com"> and replacing it for .com" target="_blank">. You can do this on all editors that have the find/replace feature. It's just a matter of finding patterns and how to replace them.

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