DOM 元素的对象表示法
在下面的示例中,DOM 元素有一个类似数组的对象,但有一点我不清楚。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
window.onload = function(){
for(var prop in document.links){
alert(prop); // It does not alert foo!
}
}
</script>
</head>
<body>
<a name="foo" href="#">foo</a>
</body>
</html>
理论上,用于访问 prop 的对象表示法类似于:obj.prop
。 在类对象数组中,对象的元素必须有数字表示法:obj[0]
和 obj.length
。
警报给出:0
、length
、item
、namedItem
。前两个来自类对象数组理论,其他两个可用于访问 props。
最后,可以像 document.links[0]
和 document.links.foo
一样找到此链接。 document.links
中没有 foo
属性。为什么?谢谢。
In following example, there is array-like object for DOM elements and there is one thing which is unclear to me.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
window.onload = function(){
for(var prop in document.links){
alert(prop); // It does not alert foo!
}
}
</script>
</head>
<body>
<a name="foo" href="#">foo</a>
</body>
</html>
In theory object notation for accessing prop is like: obj.prop
.
In object array-like there must be number notation for elements of a object: obj[0]
, and obj.length
.
And alert is giving: 0
, length
, item
, namedItem
. First two is from theory of object array-like and other two can be used for accessing props.
And, finally, this link could be found like document.links[0]
and document.links.foo
. There is no foo
prop in document.links
. Why? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
document.links.foo
不可用的原因是您使用的是name
而不是id
。如果您将标记更改为:那么这将起作用:
The reason
document.links.foo
is not available is because you're usingname
and notid
. If you change your markup to:Then this will work:
您将 DOM 元素本身传递给“alert()”。传递“name”属性怎么样?
现在,像这样迭代节点列表确实是一个坏主意:
如果您想要节点的文本内容,那么您可以尝试以下操作:
您还可以找到其子文本节点并提取它们的值。
请注意,“links”对象还将包含
标签(如果有的话)。
You're passing the DOM element itself to "alert()". What about passing the "name" attribute?
Now, it's really a bad idea to iterate through a node list like that:
If you want the text content of the node, then you can try this:
You could also find its child text nodes and extract their value.
Note that the "links" object will also include
<area>
tags, if you've got any.