Form approach(表格方式)
As scoota269 says, you should use onSubmit
instead, cause pressing enter on a textbox will most likey trigger a form submit (if inside a form)
(正如scoota269所说,您应该改用onSubmit
,因为在文本框上按Enter键最有可能触发表单提交(如果在表单内))
<form action="#" onsubmit="handle">
<input type="text" name="txt" />
</form>
<script>
function handle(e){
e.preventDefault(); // Otherwise the form will be submitted
alert("FORM WAS SUBMITTED");
}
</script>
Textbox approach(文字框方法)
If you want to have an event on the input-field then you need to make sure your handle()
will return false, otherwise the form will get submitted.
(如果要在输入字段上有一个事件,则需要确保handle()
将返回false,否则将提交表单。)
<form action="#">
<input type="text" name="txt" onkeypress="handle(event)" />
</form>
<script>
function handle(e){
if(e.keyCode === 13){
e.preventDefault(); // Ensure it is only this code that rusn
alert("Enter was pressed was presses");
}
}
</script>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…