Javascript、window.event、表单验证

Javascript、window.event、表单验证,javascript,html,Javascript,Html,这是我们教授的一个例子,我的HTML已经生锈了,所以我不确定到底发生了什么。 对于表单输入: <input type="text" name="widgets" id="widgets" size="2" value="0" onchange="calc();" onkeypress="return isNumberInput(this, event);" /> 有人能解释一下发生了什么事吗?我不太熟悉window.event、event.which、wondow.event.ke

这是我们教授的一个例子,我的HTML已经生锈了,所以我不确定到底发生了什么。
对于表单输入:

<input type="text" name="widgets" id="widgets" size="2" value="0" onchange="calc();" onkeypress="return isNumberInput(this, event);" />

有人能解释一下发生了什么事吗?我不太熟悉window.event、event.which、wondow.event.keyCode等。我不太理解逻辑。蒂亚

基本上,此代码防止用户在文本字段中输入除数字以外的任何内容。函数返回true以允许用户输入击键,返回false以防止击键。此外,还允许使用特殊字符

var key, keyChar; // declare variable to be used
if (window.event) // window.event Microsoft uses window.event. Does it exist? If so continue
    key = window.event.keyCode; // Microsoft uses window.event.keyCode to get the key the was pressed
else if (event) // other modern browsers will create an event object for you to use
    key = event.which; // event.which is the key that was pressed
else // else we can't get to the key maybe this is a full text browser? Anyways, no good exit function
    return true;
至于让您感到困惑的部分,这是一段非常古老的代码,专为旧版本的Netscape和IE设计。对于现代浏览器,您可以只使用event.keyCode,但Netscape过去使用event.which,IE过去要求您使用window.event。现代浏览器也隐藏了状态栏,使得window.status行毫无用处

var key, keyChar; // declare variable to be used
if (window.event) // window.event Microsoft uses window.event. Does it exist? If so continue
    key = window.event.keyCode; // Microsoft uses window.event.keyCode to get the key the was pressed
else if (event) // other modern browsers will create an event object for you to use
    key = event.which; // event.which is the key that was pressed
else // else we can't get to the key maybe this is a full text browser? Anyways, no good exit function
    return true;