Target _blank in all Link

不羁岁月 提交于 2019-12-10 01:38:20

问题


I've just made an html page with target _self

But now I have too many links and I want to change all link targets to _blank and it's hard for me to do. Is there is any javascript which apply on all just to write 1 time ??

Because my code is too long and it is taking too many times to change in all links. Is there is any trick?

like this

<a href="http://www.google.com"></a>
<a href="http://www.facebook.com"></a>
<a href="http://www.gmail.com"></a>
<a href="http://www.twitter.com"></a>
<a href="http://www.stackoverflow.com"></a>
<a href="http://plus.google.com"></a>

回答1:


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.




回答2:


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.




回答3:


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.)




回答4:


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!!




回答5:


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.



来源:https://stackoverflow.com/questions/24428476/target-blank-in-all-link

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