How can I open a link in a new window?

后端 未结 10 1047
不知归路
不知归路 2020-11-30 19:21

I have a click handler for a specific link, inside that I want to do something similar to the following:

window.location = url

I need this

相关标签:
10条回答
  • 2020-11-30 19:44

    This is not a very nice fix but it works:

    CSS:

    .new-tab-opener
    {
        display: none;
    }
    

    HTML:

    <a data-href="http://www.google.com/" href="javascript:">Click here</a>
    <form class="new-tab-opener" method="get" target="_blank"></form>
    

    Javascript:

    $('a').on('click', function (e) {    
        var f = $('.new-tab-opener');
        f.attr('action', $(this).attr('data-href'));
        f.submit();
    });
    

    Live example: http://jsfiddle.net/7eRLb/

    0 讨论(0)
  • 2020-11-30 19:52

    You can also use the jquery prop() method for this.

    $(function(){
      $('yourselector').prop('target', '_blank');
    }); 
    
    0 讨论(0)
  • 2020-11-30 19:55

    you will need to use window.open(url);

    references:
    http://www.htmlcodetutorial.com/linking/linking_famsupp_120.html
    http://www.w3schools.com/jsref/met_win_open.asp

    0 讨论(0)
  • 2020-11-30 19:55

    this solution also considered the case that url is empty and disabled(gray) the empty link.

    $(function() {
      changeAnchor();
    });
    
    function changeAnchor() {
      $("a[name$='aWebsiteUrl']").each(function() { // you can write your selector here
        $(this).css("background", "none");
        $(this).css("font-weight", "normal");
    
        var url = $(this).attr('href').trim();
        if (url == " " || url == "") { //disable empty link
          $(this).attr("class", "disabled");
          $(this).attr("href", "javascript:void(0)");
        } else {
          $(this).attr("target", "_blank");// HERE set the non-empty links, open in new window
        }
      });
    }
    a.disabled {
      text-decoration: none;
      pointer-events: none;
      cursor: default;
      color: grey;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <a name="aWebsiteUrl" href="http://www.baidu.com" class='#'>[website]</a>
    <a name="aWebsiteUrl" href=" " class='#'>[website]</a>
    <a name="aWebsiteUrl" href="http://www.alibaba.com" class='#'>[website]</a>
    <a name="aWebsiteUrl" href="http://www.qq.com" class='#'>[website]</a>

    0 讨论(0)
提交回复
热议问题