简体   繁体   English

文件[“某些名字”]真的有什么作用?

[英]What does document[“Some Name”] really do?

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. 对于<img><h1>标记有什么不同。 The picture src is changed as expected by the document["n1"].src line. 图片srcdocument["n1"].src行的预期进行了更改。 But the heading innerHTML is not changed as expected by the document["n2"].innerHTML line. 但是标题innerHTML没有像document["n2"].innerHTML行那样改变。 What does document["some string"] really return? document["some string"]真的会返回什么?

In JavaScript, object["string"] access the property 'string' on object . 在JavaScript中, object["string"]访问object上的属性'string' 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. 对于document对象,默认情况下将加载某些属性,例如具有name属性的元素。 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. 也就是说, name属性不是<h1>标签上的有效属性,因此文档不会将其加载到document["name"]值中。

The name attribute is valid on the following elements: name属性对以下元素有效:

  • <a> - Attribute deprecated in HTML 4, obsolete in HTML5 <a> - 在HTML 4中弃用的属性,在HTML5中已过时
  • <applet> - Element obsolete in HTML5 <applet> - HTML5中的元素已过时
  • <button>
  • <form> - Attribute deprecated in HTML 4, returned in HTML5 <form> - 在HTML 4中弃用的属性, 在HTML5中返回
  • <frame> - Element obsolete in HTML5 <frame> - HTML5中的元素已过时
  • <iframe>
  • <img> - Attribute deprecated in HTML 4, obsolete in HTML5 <img> - HTML 4中弃用的属性,HTML5中已废弃
  • <input>
  • <map>
  • <meta> - Not the same name attribute <meta> - 不同的name属性
  • <object>
  • <param> - Not the same name attribute <param> - name属性不同
  • <select>
  • <textarea>

For each of these elements, if they have a name attribute, they will be added to the document, as you can see. 对于每个元素,如果它们具有name属性,则会将它们添加到文档中,如您所见。 The preferred way to get this elements, though, is using document.getElementsByName() 但是,获取此元素的首选方法是使用document.getElementsByName()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM