如果您想引用页面中的表单对象,您可以使用“document.forms”对象,即文档中的表单对象数组。假设我们有这样的表格:
<form method="post" action="somthing.php" name="myContactForm" id="contact_form">
<input type="text" name="custList" id="custListId" />
</form>
要以正确的方式访问该值,您可以使用以下任何一种方法:
首先访问表单,然后访问元素。
var form = document.forms['myContactForm']; // use the 'name' attribute as the array key
// or if this is the first form appeared in the page. otherwise increase the index number to match the position of your target form.
var form = document.forms[0];
// or access the form directly
var form = document.getElementById('contact_form');
// now get the element, from the form. you can access form elements, by using their name attribute as the key in the elemetns array property of the form object.
var cust = form.elements['custList'].value();
或者您可以直接访问表单元素,无需任何表单。您可以直接通过其 id 引用文档中的任何元素。这里不需要表格。
var cust = document.getElementById('custListId');
所有这些语句都是在 IE、firefox、opera、chrome 等上运行的有效 JavaScript。
但是,您可以在 IE 中引用表单对象,只需调用其“名称”属性即可。所以这条线在 IE 中有效(正如你所说,chrome。我不知道 chrome 处理它):
var cust = myContactForm.custList.value();
IE 尝试通过匹配元素的 'name' 属性来将未知的窗口级别属性(如 myContactForm )映射到元素。