【问题标题】:why this javascript is line is Right and the other isn't为什么这个 javascript 行是正确的,而另一个不是
【发布时间】:2009-10-18 06:49:35
【问题描述】:

javascript 与>

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

这行得通……

为什么它会起作用但是......

var customer=(form1.custList.value);

我收到一个错误,指出 form1 未定义。

特别是为什么这在 IE 和 Chrome 中有效,但在 Firefox 中无效。 对我来说似乎很清楚,但我不是脚本引擎

只是想了解

【问题讨论】:

  • 不知道怎么感谢大家。所有的回复确实帮助我更好地理解了这一点。
  • @scott - 不客气。有一个简单的方法来感谢大家 - 接受解决您问题的答案(使用它旁边的复选标记)。您还可以对对您有帮助的答案投票(但您需要 15 声望)。

标签: javascript forms undefined


【解决方案1】:

如果您想引用页面中的表单对象,您可以使用“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 )映射到元素。

【讨论】:

    【解决方案2】:

    我认为 IE/Chrome/Opera 将 id="form1" 错误地解释为 name="form1"(反之亦然?)以解释遗留标记。

    我会依赖 dom 0 级别的属性访问,例如 form1.custList,而是使用 document.getElementById。如果输入太长,请定义一个方法来执行它.. 例如

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

    【讨论】:

      【解决方案3】:

      因为第二个成语不是标准的,而getElementById是标准的,所以必须每个浏览器都支持才能说它与javascript兼容。

      另外,如果我没记错的话,第二个应该是document.form1.custList.value

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

          Internet Explorer 按名称将所有表单元素作为属性填充到window 对象中,这是脆弱的、不兼容的、难以巧妙使用的——这也是使您的第二个示例有效的原因。其他浏览器只是采取完全不实现该接口的干净路线,让您拥有正确的 DOM 功能。或者工具包。 jQuery 真的很不错。 ;)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-10-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-04-07
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多