Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript通过按键或返回键从输入转到URL_Javascript_Html_Forms_Url_Input - Fatal编程技术网

javascript通过按键或返回键从输入转到URL

javascript通过按键或返回键从输入转到URL,javascript,html,forms,url,input,Javascript,Html,Forms,Url,Input,我有一个带有输入字段的页面,我想将用户发送到他们在输入中输入的URL,并在末尾附加-.html。我的HTML如下所示: <form name="codeform"> <input type="text" id="code" name="code" autofocus> </form> <a href="#" class="button" id="submit">SUBMIT</a> 当用户单击按钮时,脚本按预期工作,用户进入页面。

我有一个带有输入字段的页面,我想将用户发送到他们在输入中输入的URL,并在末尾附加-.html。我的HTML如下所示:

<form name="codeform"> 
<input type="text" id="code" name="code" autofocus>
</form>

<a href="#" class="button" id="submit">SUBMIT</a>
当用户单击按钮时,脚本按预期工作,用户进入页面。但我也希望脚本在按下回车键时执行。现在,当按下return键时,它会尝试提交表单,最后我得到一个查询字符串


无论是否按下按钮或返回键,将用户发送到页面的最佳方式是什么?

您可以添加一个只在enter(键代码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';
    }
});

因为您的
a.button
位于表单的外部,所以需要向表单和
a.button
添加触发器。然后只需检测到错误,就可以完成

$('form')。提交(函数(e){
e、 预防默认值();
console.log(window.document.codeform.code.value+'.html')
});
$('form').keydown(函数(e){
如果(e.which==13){
console.log(window.document.codeform.code.value+'.html')
}
});
$('#submit.button')。单击(函数(){
console.log(window.document.codeform.code.value+'.html')
});

由于您将逻辑附加到按钮单击()事件,因此只需将keypress()事件附加到输入框,即可随后执行按钮单击

$("#code").keypress(function(event) {
    if (event.which == 13) {
        event.preventDefault();
        $('#submit').click();       
    }
});

然而,为了整洁起见,我通常更喜欢将逻辑从click事件移动到一个单独的函数中,并从click()和keypress()事件调用该函数

不要使用$(“$submit”)。单击(..),将“action”属性添加到表单中。谢谢Riya!现在看起来很明显,但我一辈子都想不出来!为什么不在表单中使用提交按钮?是的,我切换到了提交按钮。
$("#code").keypress(function(event) {
    if (event.which == 13) {
        event.preventDefault();
        $('#submit').click();       
    }
});