Document.getElementById()返回名称等于id指定的元素 [英] Document.getElementById() returns element with name equal to id specified
问题描述
我以前在这个SO 中提到过关于IE6 / 7(和一些版本的Opera)的有趣行为,在 document.getElementById
中可以找到一个元素,它的名称
属性被定义,但不是 id
属性,这样
I have previously mentioned in this SO about the funny behavior for IE6/7 (and some versions of Opera) in that document.getElementById
can find an element whose name
attribute is defined but not the id
attribute, such that
function f() {
document.getElementById("a1").value = ...;
}
...
<input name="a1" ...></input>
实际上可以在这些版本中使用。
actually works in these versions.
通过网络搜索,我发现Chris Bloom的这个错误报告 ,其中名为Milo van der Leij的用户指出以下内容(由他在这个w3c规格):
Searching through the net I found this bug report by Chris Bloom, in which a user named Milo van der Leij points out the following (as referred by him in this w3c spec):
在他们的防御中:id和name属性共享相同的名称空间。
这是什么意思,id和name属性共享同一个命名空间?为什么IE6 / 7 / Opera在这个JS引擎中实现这个行为就足够了?
What does it mean that the id and name attributes share the same namespace? Why would this condition be sufficient for IE6/7/Opera implement this behavior in their JS engine?
推荐答案
术语同名命名空间
意味着名称和ids不是完全独立的。您可以在一个特定对象上使用相同的名称
和 id
,但不能使用名称=foo
,另一个对象上的 id =foo
这就造成了冲突。
The term "same namespace"
means that names and ids are not completely separate. You can use the same name
and id
on one particular object, but you cannot use name="foo"
on one object and id="foo"
on another object. That creates a conflict.
这只是浏览器决定实施的一种方式。每个元素还包含一个包含dom元素的id的全局变量。这就是他们实现事情的方式。它不是标准的,它不是在更现代的浏览器中完成的事情(除了一些向后兼容性)。
It's just the way those browsers decided to implement things. There's also a global variable for each element with an id that contains the dom element. That's just the way they implemented things. It wasn't standard, it isn't the way things are done in more modern browsers (except for some backward compatibility).
使用 id
要检索的任何DOM元素的值。在发布的表单中使用名称
服务器标识的值。
Use id
values for any DOM elements you want to retrieve. Use name
values for server identification in posted forms.
如果您的代码在名称和ids之间没有冲突不要在一个对象上使用 id
,而在另一个对象上使用相同的名称
,而且通常不会给予特定元素相同的问题 name
和 id
。
Your code will have no conflicts between names and ids if you don't use an id
on one object and the same name
on another object, and there generally isn't an issue with giving a particular element the same name
and id
.
这篇关于Document.getElementById()返回名称等于id指定的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!