简体   繁体   中英

html/javascript: Hiding link destination and opening link in new tab

I am using the following javascript (provided by m59 in this previous answer) to hide the destination of a link which usually shows up at the bottom of the browser window when hovering over a link:

<div>
    <a data-href="http://www.google.com/"> LINK </a>

    <script type="text/javascript">
        var anchors = document.querySelectorAll('a[data-href]');

        for (var i=0; i<anchors.length; ++i) {
          var anchor = anchors[i];
          var href = anchor.getAttribute('data-href');
          anchor.addEventListener('click', function() {
            window.location = href;
          });
        }
    </script>
</div>

This works perfectly fine, but I would like the link to open in a new tab as well. How do I have to change the script in order to do so?

I tried using window.open('href','_blank'); instead of window.location = href; which did not work.

除非我错过了一些东西,否则最明显的事情就是向该锚点添加一个目标:

<a data-href="http://www.google.com/" target="blank"> LINK </a>

This is how to do it (try it on your code, stackoverflow blocks new tabs and links)

 var anchors = document.querySelectorAll('a[data-href]'); for (var i=0; i<anchors.length; ++i) { var anchor = anchors[i]; var href = anchor.getAttribute('data-href'); anchor.addEventListener('click', function() { window.open(href,'',''); }); } 
 <div> <a data-href="http://www.google.com/"> LINK </a> </div> 

You can see here , that syntax of window.open is:

var window = window.open(url, windowName, [windowFeatures]);

So to open link in new tab you should use something like:

var myNewTab = window.open(url, '_blank');

It will not work if you window is opened as '_blank'

Did you try window.open(href) ?

ie In your example, href is a string (there are single quotes around it) as opposed to a variable.

Why not just use an onclick event handler to redirect the user?

<a href="" onclick="onClick">link</a>

function onClick(e) {
  e.preventDefault();
  document.location.href='www.google.ca';
}

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