javascript 我需要Javascript函数来禁用回车键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6017350/
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
I need Javascript function to disable enter key
提问by Ali Taha Ali Mahboub
I need to use JS function to disable enter key. I'm currently facing an issue with my Spring form
我需要使用 JS 函数来禁用回车键。我目前的 Spring 表单存在问题
<form:textarea path="name" onkeypress="return noenter()"
here is the function I currently using
这是我目前使用的功能
<script> function noenter() { alert("Testing");
return !(window.event && window.event.keyCode == 13);
} </script>
for some reason, the alert is working when I press on Enter key, but still facing same exception
出于某种原因,当我按下 Enter 键时警报正在工作,但仍然面临同样的异常
HTTP Status 415 -
type Status report
message
description The server refused this request because the request entity is in a format not supported by the requested resource for the requested method (). Apache Tomcat/6.0.29
HTTP 状态 415 -
类型状态报告
信息
描述 服务器拒绝此请求,因为请求实体的格式不为所请求方法的请求资源所支持 ()。Apache Tomcat/6.0.29
回答by ?ime Vidas
This should work:
这应该有效:
Markup:
标记:
<form:textarea path="name" onkeypress="return noenter(event)">
JavaScript:
JavaScript:
function noenter(e) {
e = e || window.event;
var key = e.keyCode || e.charCode;
return key !== 13;
}
Live demo:http://jsfiddle.net/Fj3Mh/
现场演示:http : //jsfiddle.net/Fj3Mh/
回答by Charles Lambert
you need to address this in the keyup and keydown event. The browser uses the enter key independent of the actual web page. So you will need to stop event propagation at the keyup or keydown event. By the time the keypress event has been emitted the browser itself has received it and there is no way to keep it from processing. This is specific to the enter key and a few others. Character keys such as 'a' and 'b' do not suffer from this problem.
您需要在 keyup 和 keydown 事件中解决这个问题。浏览器使用独立于实际网页的回车键。因此,您需要在 keyup 或 keydown 事件中停止事件传播。当 keypress 事件发出时,浏览器本身已经收到它,并且没有办法阻止它处理。这是特定于回车键和其他一些键的。诸如“a”和“b”之类的字符键不会遇到此问题。
回答by Arjun Solanki
<script type="text/javascript">
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>