jQuery add target=“_blank” for outgoing link

后端 未结 15 1741
滥情空心
滥情空心 2020-12-13 04:01

I need some help to create jquery script :)
I have some of link like this on my HTML.

Google


        
相关标签:
15条回答
  • 2020-12-13 04:50
    <div id="myLinks"><a href="http://google.com">Google</a><a href="/">Home</a><a href="http://www.gusdecool.com/">Home</a>
    <a href="contactus.html">Contact Us</a></div>
    <script type="text/javascript">
    jQuery(document).ready(function(){
    jQuery('#myLinks a').attr('target', '_blank');
    });
    </script>
    
    0 讨论(0)
  • 2020-12-13 04:54

    You could use jQuery's $.each function to iterate over all Anchor tags, perform the needed check and set the "target" attribute using $(this).attr("target","_blank");

    Example (Not tested but should work):

    $('a').each(function(index) {
        var link = $(this).attr("href");
        if(link.substring(0,7) == "http://")
            $(this).attr("target", "_blank");
    });
    

    Shai.

    0 讨论(0)
  • 2020-12-13 04:55

    Here's a fiddle demonstrating an answer using raw JS (not jQuery): http://jsfiddle.net/Xwqmm/

    And here's the code:

    var as = document.getElementsByTagName('a');
    var re = /^https?:\/\/([^\/]*)\//;
    for (var i = 0, l = as.length; i < l; i++) {
        var href = as[i].href;
        var matches = href.match(re);
        if (matches[1] && matches[1] != "gusdecool.com") {
            as[i].setAttribute("target","_blank");
        }
    }
    
    0 讨论(0)
提交回复
热议问题