简体   繁体   中英

re-write all links on page to open in new tab through javascript

To make all links in a page non-clickable, I use the following code:

<html>
<body>
<script>
document.body.onclick=function(e){
e.preventDefault();
return false;
}
</script>
<a href="http://www.google.com">Link 1</a>
<a href="http://www.ebay.com">Link 2</a>
</body>
</html>

Now I know that to make a link open in a new tab we can use:

target="_blank"

But that is not the question here, the question is, how can I:

1) Make all links clickable through javascript after first making them non-clickable as shown above.

2) Use javascript to re-write all the URLs in the page to open in a new tab, AKA how can I use javascript to add the necessary target="_blank" attribute to all links in any HTML page?

thanks!

 <html> <body> <script> document.body.onclick=function(e){ // or addEventListener e.preventDefault(); return false; } window.onload=function() { document.body.onclick=null; var links = document.querySelectorAll("a"); for (var i=0;i<links.length;i++) { links[i].target="_blank"; } } </script> <a href="http://www.google.com">Link 1</a> <a href="http://www.ebay.com">Link 2</a> </body> </html 

or in jQuery use attr :

$("body").on("click",function(e){
  e.preventDefault();
  return false; // not necessary
});
$(function() {
  $("body").off("click");
  $("a").attr("target")="_blank";
})

如果可以启用对链接的单击,则可以通过将此标签添加到页面<head>来更改默认目标:

<base target="_blank" />

It is easy like this:

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

But you need to put it at the end of the document.

But if you don't like it to be at the end of the document and also want it to work across all browsers you can do something like this:

var DOMReady = function(a,b,c){b=document,c='addEventListener';b[c]?b[c]('DOMContentLoaded',a):window.attachEvent('onload',a)}

DOMReady(function () {
  var aList = document.getElementsByTagName('a');
  for(var i = 0 ; i < aList.length; i++){
    aList[i].setAttribute('target', '_blank');
  }
});

The DOMReady function is for when the document structure was shaped in the dom. This part was used from another code in this page: Tiny Cross Browser DOM Ready

Just add:

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

instead of

document.body.onclick=function(e){
    e.preventDefault();
    return false;
}

BUT, keep in mind that you need to include jQuery to be able to do so.

将每个锚点的target属性设置为'_blank'

document.querySelectorAll("a").forEach(a => a.target = '_blank' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM