javascript 在表单输入上按回车键使其失去焦点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31305599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Press enter on form input to make it lose focus
提问by claytonkirlew
I have a form with an input box and hidden submit field:
我有一个带有输入框和隐藏提交字段的表单:
<form action="javascript:void(0);">
<input type="text">
<input type="submit" style="display:none;">
</form>
I would like to make it so that when you click enter, the input box simply loses focus.
我想让它当你点击回车时,输入框只是失去焦点。
How can I accomplish this?
我怎样才能做到这一点?
回答by prashant
Try this out. Please note that you need to include jquery file for this to work.
试试这个。请注意,您需要包含 jquery 文件才能使其工作。
<form action="javascript:void(0);">
<input type="text" id="txtFocus">
<input type="submit" style="display:none;" id="btnHidden">
</form>
<script>
$("#btnHidden").on('click', function() {
$('#txtFocus').blur();
});
</script>
回答by baao
Give your input an id for convenience, and you can do this with this little function using plain javascript
为方便起见,为您的输入提供一个 id,您可以使用普通的 javascript 使用这个小函数来完成此操作
<form action="javascript:void(0);">
<input id="input1" type="text">
<input type="submit" style="display:none;">
</form>
<script>
document.getElementById('input1').addEventListener('keyup',function(e){
if (e.which == 13) this.blur();
});
</script>