为什么我们在javascript中使用document.form [1(或)2 ...]以外的document.form [0]

时间:2014-12-04 06:33:56

标签: javascript html

为什么我们在document.form [0]中使用0。如果我使用1代替0,那么任何人都无法解释。 我的代码是:

<!DOCTYPE html>
<html>
<head>
<script>
function preferedBrowser() {
//here if i use document.forms[1] it will not work
prefer = document.forms[0].browsers.value;
alert("You prefer browsing internet with " + prefer);
}
</script>
</head>
<body>

<form>
Choose which browser you prefer:
<select id="browsers" onchange="preferedBrowser()">
<option>Chrome</option>
<option >Internet Explorer</option>
<option>Firefox</option>
</select>
</form>

</body>
</html>

6 个答案:

答案 0 :(得分:1)

这是因为你的html页面中只有一个<form>对象。 该数组基于零。

答案 1 :(得分:1)

document.form是文档正文中表单元素的数组,数组以索引0开头,因为你只有1个表单,document.form数组中只有1个元素,所以它是index是0

答案 2 :(得分:1)

在具有多种形式的HTML页面中

您可以通过索引0 i,e document.forms [0];

访问第一个表单

和第二个索引1,依此类推。

For example follow this link

答案 3 :(得分:1)

document.forms 返回文档所有形式的集合。因此,当它返回一个集合时,你需要使用它的索引来处理特定的表单。还有其他方法可以获取特定表单,即使用 id 属性

<form id="myForm"></form>

var aForm = document.getElementById("myForm");

在您的情况下,它是一个单独的表单,因此您必须使用0索引来解决该问题。但在许多网页中,开发人员需要多种形式。所以你可能需要使用正确的索引。

使用它的id属性调用特定表单仍然是最好的。谁想用号码而不是名字来打电话。因为id对每个元素都是唯一的,所以你可以从中获得很多好处。

答案 4 :(得分:0)

Javascript中的数组从索引“0”开始而不是从“1”开始。因此,如果您只有一个表单,则可以从“0th”索引访问它。如果您有两个表单,则可以使用document.form [1] ....等等来访问第二个表单...

答案 5 :(得分:0)

document.forms,复数形式。它是一个类似于数组的数据结构(实际上是HTMLCollection),并且是从零开始的。