gpt4 book ai didi

javascript从按下按钮或返回键的输入转到URL

转载 作者:行者123 更新时间:2023-11-27 23:19:10 25 4
gpt4 key购买 nike

我有一个带有输入字段的页面,我想将用户发送到他们在输入中输入的 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>

关于javascript从按下按钮或返回键的输入转到URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41842809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com