我想要一个人们可以输入值的文本字段。然后我想打开一个href打开他们输入的网址。
非常类似于这个小提琴,但我希望href只是用户输入的输入值。
小提琴:
<a href="/base/url" target="blank" id="baseUrl">Link Text</a>
<input type="text" id="appendUrl" />
$(function() {
$('#baseUrl').click( function() {
window.location = $(this).attr('href') + '/' + $('#appendUrl').val();
return false;
});
});
答案 0 :(得分:0)
修改:要在输入外部网址时回答您的问题,您将使用此处的功能: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>