Jquery : How to prevent prefix addition to address within an `<a>` Tag

强颜欢笑 提交于 2021-02-08 11:41:27

问题


I have a HTML <a> Tag as follows:

<a id="ext_link" href="www.google.com">GOOGLE HOME</a>

And I am using JQUERY to open link in a new window. The JQUERY is as below:

$(document).ready(function(){
    $("#ext_link").click(function(e){
        e.preventDefault();
        window.open($(this).attr("href"));
    });
});

When I use <a id="ext_link" href="http"//www.google.com">GOOGLE HOME</a> it works fine, but when I use <a id="ext_link" href="www.google.com">GOOGLE HOME</a> a new window opens and the addressbar contains http://localhost/app/www.google.com which is wrong address obviously...

How can I prevent the automatic addition of http://localhost/app/ at the beginning.


回答1:


You can use a regex to test if your href start with http:// or https://, if not then add http://:

$(document).ready(function(){
    $("#ext_link").click(function(e){
        e.preventDefault();
        var url = $(this).attr("href");
        if(!/^(http|https):\/\//.test(url)){
            url = "http://" + url;
        }
        window.open(url);
    });
});



回答2:


Check if the href doesn't contain the http:// and add it like so:

$(document).ready(function(){
    $("#ext_link").click(function(e){
        e.preventDefault();
        var url = $(this).attr("href");
        if(!/^https?:\/\//.test(url)){
            url = "http://" + url;
        }
        window.open(url);
    });
});

You can add more protocols but https?:// should be enough. Or you could just use // as many modern browsers use it and gets the appropriate protocol.



来源:https://stackoverflow.com/questions/22370481/jquery-how-to-prevent-prefix-addition-to-address-within-an-a-tag

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