0

我在网页上有两个文本框和两个按钮。

每个文本框都有自己的 keypress 函数,用于检查返回键并调用特定的 javascript 函数。

但问题是,如果我开始在任何文本框中输入并点击返回,这两个函数都会被调用。这仅在 Internet Explorer 中发生。

Onkeypress 被称为输入标签的属性

onkeypress="if(event.keyCode==13) submitEmail();"

onkeypress="if(event.keyCode==13) login();"

谢谢

4

2 回答 2

2

This is because of event bubbling. When an event happens on an element, it also happens on all the elements that contain it, in sequence walking up the DOM tree. So pressing Return on the input box also presses return on the window.

If you add return false; to the onkeypress attribute of the input element, that will prevent bubbling.

<input ... onkeypress="if(event.keyCode==13) { submitEmail();return false; }">
于 2013-06-27T21:45:11.287 回答
0

您可以尝试在脚本标签或外部 js 文件中设置它们,在设置按键功能之前针对每个输入。

<input type="text" id="email">
<input type="text" id="login">

<script>  
var emailBox = document.getElementById("email")
emailBox.onkeypress = function(e){
  if(e.keyCode == 13) submitEmail();
}

var loginBox = document.getElementById("login")
loginBox.onkeypress = function(e){
  if(e.keyCode == 13) login();
}
</script>
于 2013-06-27T21:49:44.663 回答