文件[“有些名字”]真的做什么?(What does document[“Some Name”] really do?)

这个代码

<img name="n1" src="" /> <h1 name="n2">a header</h1> <script> document["n1"].src = "http://x.y/picture.jpg"; document["n2"].innerHTML = "Boo"; </script>

对<img>和<h1>标签有不同的作用。 图片src按照document["n1"].src行的预期更改。 但是,标题innerHTML不会像document["n2"].innerHTML行那样发生变化。 document["some string"]真的返回什么?

This code

<img name="n1" src="" /> <h1 name="n2">a header</h1> <script> document["n1"].src = "http://x.y/picture.jpg"; document["n2"].innerHTML = "Boo"; </script>

Does something different for the <img> and <h1> tags. The picture src is changed as expected by the document["n1"].src line. But the heading innerHTML is not changed as expected by the document["n2"].innerHTML line. What does document["some string"] really return?

最满意答案

在JavaScript中, object["string"]访问object上的属性'string' 。 这可以用来访问许多不同对象的许多不同属性,就像将对象视为值的哈希映射一样。 对于document对象,默认情况下会加载某些属性,如具有name属性的元素。 至少对于某些浏览器(我不知道哪个子集)。

也就是说, name属性不是<h1>标签上的有效属性,因此文档不会将其加载到document["name"]值中。

name属性在以下元素上有效:

<a> - HTML 4中已弃用的属性,已在HTML5中废弃 <applet> - 元素在HTML5中已过时 <button> <form> - 在HTML 4中弃用的属性, 在HTML5中返回 <frame> - 元素在HTML5中已过时 <iframe> <img> - HTML 4中不推荐使用的属性,HTML5中已废弃 <input> <map> <meta> - 不同的name属性 <object> <param> - 不同的name属性 <select> <textarea>

对于这些元素中的每一个,如果他们具有name属性,就会将其添加到文档中,如您所见。 但是,获取此元素的首选方法是使用document.getElementsByName()

In JavaScript, object["string"] access the property 'string' on object. This can be used to access many different properties on many different objects, and is like treating the object as a hash map of values. For the document object, this will get loaded with certain properties by default, like elements with the name attribute. At least for some browsers (I have no idea which subset).

That said, the name attribute isn't a valid attribute on an <h1> tag, so the document does not load that into document["name"] value.

The name attribute is valid on the following elements:

<a> - Attribute deprecated in HTML 4, obsolete in HTML5 <applet> - Element obsolete in HTML5 <button> <form> - Attribute deprecated in HTML 4, returned in HTML5 <frame> - Element obsolete in HTML5 <iframe> <img> - Attribute deprecated in HTML 4, obsolete in HTML5 <input> <map> <meta> - Not the same name attribute <object> <param> - Not the same name attribute <select> <textarea>

For each of these elements, if they have a name attribute, they will be added to the document, as you can see. The preferred way to get this elements, though, is using document.getElementsByName()

更多推荐

document,src,innerHTML,电脑培训,计算机培训,IT培训"/> <meta name="descri