编辑:如果他们输入了外部 URL,要回答您的问题,您将使用此处找到的功能:Fastest way to detect external URLs?
function isExternal(url) {
var match = url.match(/^([^:\/?#]+:)?(?:\/\/([^\/?#]*))?([^?#]+)?(\?[^#]*)?(#.*)?/);
if (typeof match[1] === "string" && match[1].length > 0 && match[1].toLowerCase() !== location.protocol) return true;
if (typeof match[2] === "string" && match[2].length > 0 && match[2].replace(new RegExp(":("+{"http:":80,"https:":443}[location.protocol]+")?$"), "") !== location.host) return true;
return false;
}
结合当前代码,这使得:
function isExternal(url) {
var match = url.match(/^([^:\/?#]+:)?(?:\/\/([^\/?#]*))?([^?#]+)?(\?[^#]*)?(#.*)?/);
if (typeof match[1] === "string" && match[1].length > 0 && match[1].toLowerCase() !== location.protocol) return true;
if (typeof match[2] === "string" && match[2].length > 0 && match[2].replace(new RegExp(":("+{"http:":80,"https:":443}[location.protocol]+")?$"), "") !== location.host) return true;
return false;
}
$(function () {
// When the input field changes value
$('#text').blur(function(){
// Check if the link is external:
if(isExternal($('#text').val())){
// Set the attribute 'href' of the link to the value of the input field
$('#link').attr('href', $('#text').val());
}
else
{
// Show an error if it's not external
alert('Link is not external!');
}
});
});
<input type="text" id="text"> <a href="#" id="link">Link</a>
小提琴:http: //jsfiddle.net/BMDKr/6/