2009-10-18 54 views
1

JavaScript和>为什么这个JavaScript是线是正确的,另一种是不

var customer=document.getElementById('custList').value; 

和工程...

为什么它的工作,但...

var customer=(form1.custList.value); 

我收到一个错误,说明form1未定义。

特别是为什么这个工作在IE和Chrome而不是Firefox。 看起来就像明确提出给我,但我不是一个脚本引擎

只是想了解

+0

不知道如何感谢你们所有人。所有的答复真的帮助我更好地理解这一点。 – datatoo 2009-10-18 07:17:31

+0

@scott - 欢迎您。有一种简单的方法来感谢所有人 - 接受解决您问题的答案(使用旁边的复选标记)。您也可以对帮助您的答案投票(但您需要15点声望)。 – Kobi 2009-10-18 07:31:07

回答

1

如果要在页面中引用表单对象,则可以使用'document.forms'对象,即文档中的表单对象数组。假设我们有一个形式是这样的:

<form method="post" action="somthing.php" name="myContactForm" id="contact_form"> 
    <input type="text" name="custList" id="custListId" /> 
</form> 

到以正确的方式访问该值,您可以使用下列任一方法: 第一acccess形式,那么元素。

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,歌剧,铬等 但你可以参考表单对象在IE中,仅通过调用其“name”属性运行有效的JavaScript。所以这条线在IE工作(和你说,铬我不知道铬处理它。):

var cust = myContactForm.custList.value(); 

IE试图通过匹配来映射未知的窗口级别的属性(如myContactForm)以元素的'name'属性。

1

我相信,IE/Chrome浏览器/歌剧错误地解释ID =“form1的”作为名称=“form1的”(反之亦然?)来考虑遗留标记。

依靠DOM 0级属性访问诸如form1.custList,而使用document.getElementById。如果它太长输入,定义要做到这一点的方法..如

function getId(id) { return document.getElementById(id) } 
1

因为第二个成语不规范,而getElementById是,所以它必须通过每个浏览器所支持的说是JavaScript的兼容。

另外,如果我没有弄错,第二个应该是document.form1.custList.value

0

Internet Explorer以自己的方式做了很多事情。无论如何,第一种方法是正确的方法(使用getElementById)。
为了向后兼容,许多这些“错误”仍然有效,但不应该使用它们。
浏览器之间仍然存在差异。使用JavaScript框架(如jQuery)在这里有很大的帮助,它被写入跨浏览器(记录,您的代码将使用jQuery $('#custList').val();

0

Internet Explorer将所有表单元素按名称作为属性的window对象,这些属性是脆弱的,不兼容的,很难与任何技巧一起使用 - 什么让你的第二个例子工作。其他浏览器只是简单地使用完全不实现该接口的干净路由,为您留下适当的DOM功能。或者一个工具包。 jQuery真的很不错。 ;)