[英]Javascript/Jquery to go to URL from <input> and <datalist>
[英]javascript go to URL from input on button press or return key
我有一个带有输入字段的页面,我想将用户发送到他们在输入中输入的 URL,并在末尾附加 -.html。 我的 HTML 如下:
<form name="codeform">
<input type="text" id="code" name="code" autofocus>
</form>
<a href="#" class="button" id="submit">SUBMIT</a>
还有我的 javascript:
$('#submit').click(function () { location.href = window.document.codeform.code.value + '.html'; });
当用户单击按钮时,脚本按预期工作并且用户转到该页面。 但我也希望在按下返回键时执行脚本。 现在,当按下返回键时,它会尝试提交表单,我最终得到一个查询字符串。
无论按下按钮还是返回键,将用户发送到页面的最佳方式是什么?
因为您的a.button
在表单之外,所以您也需要向表单和a.button
添加触发器。 然后只需检测Enter keycode ,就完成了。
$('form').submit(function(e) { e.preventDefault(); console.log(window.document.codeform.code.value + '.html') }); $('form').keydown(function(e) { if (e.which == 13) { console.log(window.document.codeform.code.value + '.html') } }); $('#submit.button').click(function() { console.log(window.document.codeform.code.value + '.html') });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <form name="codeform" id="codeform"> <input type="text" id="code" name="code" autofocus> </form> <a href="#" class="button" id="submit">SUBMIT</a>
您可以添加一个仅在输入时运行的 keydown 侦听器(键码 13),然后阻止默认的表单提交操作:
$('#submit').click(function () { location.href = window.document.codeform.code.value + '.html'; });
$('#code').keydown(function (event) {
if(event.which==13){
event.preventDefault();//prevents form submission
location.href = window.document.codeform.code.value + '.html';
}
});
由于您将逻辑附加到按钮 click() 事件,您可以简单地将 keypress() 事件附加到输入框以随后执行按钮单击。
$("#code").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
$('#submit').click();
}
});
但是,为了整洁,我通常更喜欢将逻辑从 click 事件移动到一个单独的函数中,并从 click() 和 keypress() 事件中调用该函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.