带有>的javascript
var customer=document.getElementById('custList').value;
那行得通……
为什么它有效但是...
var customer=(form1.custList.value);
我收到一个form1
未定义的错误。
尤其是为什么这在 IE 和 Chrome 中有效,但在 Firefox 中无效。对我来说似乎很清楚,但我不是脚本引擎
只是想了解
带有>的javascript
var customer=document.getElementById('custList').value;
那行得通……
为什么它有效但是...
var customer=(form1.custList.value);
我收到一个form1
未定义的错误。
尤其是为什么这在 IE 和 Chrome 中有效,但在 Firefox 中无效。对我来说似乎很清楚,但我不是脚本引擎
只是想了解
我相信 IE/Chrome/Opera 错误地将 id="form1" 解释为 name="form1" (反之亦然?)以解释遗留标记。
我不会依赖 dom 0 级别的属性访问,例如form1.custList
使用document.getElementById
. 如果输入时间太长,请定义一个方法来执行它.. 例如
function getId( id ) { return document.getElementById(id) }
因为第二个成语不是标准的,while getElementById
is,所以它必须被每个浏览器支持才能说它与javascript兼容。
另外,如果我没记错的话,第二个应该是document.form1.custList.value
.
如果要引用页面中的表单对象,可以使用“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 尝试通过匹配元素的“名称”属性将未知的窗口级别属性(如 myContactForm )映射到元素。
Internet Explorer 以它自己的方式做了很多事情。无论如何,第一种方法是正确的方法(使用getElementById
)。
为了向后兼容,许多这些“错误”仍然有效,但您不应该使用它们。
浏览器之间仍然存在差异。使用 JavaScript 框架(如jQuery)在这里有很大帮助,它被编写成可以跨浏览器运行(为了记录,您的代码将$('#custList').val();
使用 jQuery)
Internet Explorer 按名称将所有表单元素window
作为属性填充到对象中,这是脆弱的、不兼容的、难以巧妙使用的——这也是使您的第二个示例有效的原因。其他浏览器只是采用完全不实现该接口的干净路线,为您留下正确的 DOM 功能。或者工具包。jQuery 真的很不错。;)