问题
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