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

北战南征 提交于 2019-12-11 04:52:07

问题


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.


回答1:


Unless im missing something, the most obvious thing to do is add a target to that anchor:

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



回答2:


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>



回答3:


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'




回答4:


Did you try window.open(href)?

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




回答5:


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


来源:https://stackoverflow.com/questions/45677188/html-javascript-hiding-link-destination-and-opening-link-in-new-tab

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