Javascript:在IE中尝试使用圆括号而不是方括号访问表单属性

Javascript: Trying to access form attributes with round brackets instead of square brackets works in IE

本文关键字:方括号 访问 属性 表单 访问表 圆括号 IE Javascript      更新时间:2023-09-26

我希望我能正确地解释这个…

下面的网页包含一个带有onSubmit处理程序的表单。onSubmit处理程序是一个总是返回false的函数,这意味着表单永远不应该被提交。但这只适用于IE8(可能也适用于其他版本的IE)。

要在Firefox和Chrome中工作,我必须将警报更改为:

alert(foo["firstName"].value);

我明白为什么使用方括号是正确的形式,因为形式是一个关联数组。

  • 但是为什么在FF和Chrome中提交表单(因为form("firstName")显然是错误的)?
  • 是否有我可以捕获的错误?(我在Firebug中看不到任何明显的东西)
  • 是否有办法确保仅在true返回时提交表单?

感谢
<html>
<head>
<script>
function alwaysReturnFalse() {
    alert(foo("firstName").value);
    return false;
}
</script>
</head>
<body>
<form name="foo" onSubmit="return alwaysReturnFalse();">
    First name: <input name="firstName" type="text" value="Bob"/><br/>
    Last name: <input name="lastName" type="text"/><br/>
    <input type="submit" value="Submit"/>
</form>
This form has an onSubmit handler that always returns false - meaning the form should never submit.<br/>
It works in IE8 - e.g. the onSubmit handler executes an alert() and then returns false.<br/>
It fails in Firefox and Chrome - e.g. the form is submitted.
</body>
</html>

提交表单是因为其他浏览器抛出错误。错误导致函数提前退出。结果,代码没有达到返回false,所以表单提交。