document常用属性及属性集合
上一篇博文说删除结点信息时,有一行代码**document.body.removeChild(deleteNode)**,那**document.body**是什么呢?body跟document什么关系呢?今天说说常用的document属性和集合属性。所谓document属性是指那些单的属性信息,它指代的是单个的对象;集合属性指的是document对象里面的那些可以归为集合的子对象。
document.title
<html>
<head>
<title>Attribute</title>
</head>
<body>
<script>
alert(document.title);
</script>
</body>
</html>
上面的代码,会在页面加载完成后,弹一个alert框出来,那里面内容是什么呢?
执行以下,看看结果
![SouthEast][]
弹出了title的内容,那说明document.title 指向了html页面中title标签的内容。
打个断点看看,document还有哪些属性信息?
断点打到alert(document.title);行,并对document进行监视
![SouthEast 1][]
展开document对象,可以看到
![SouthEast 2][]
document的属性和集合属性太多,暂时先列这几个看看。
document.bgColor
像document.bgColor 表示背景颜色,当前值为十六进制表示的\#ffffff,我们给页面添加个背景色,然后再将背景色打印出来看看,将代码修改为
<html>
<head>
<title>Attribute</title>
</head>
<body bgColor="#CCDDAA">
<script>
alert(document.bgColor);
</script>
</body>
</html>
弹出框效果为
![SouthEast 3][]
document.anchors
一个集合类的属性document.anchors 获取所有的超链接的集合
<html>
<head>
<title>Attribute</title>
</head>
<body bgColor="#CCDDAA">
<a href="http://www.baidu.com" name="clj">百度</a></br>
<a href="http://www.google.com" name="clj">谷歌</a></br>
<a href="http://www.gougou.com" name="clj">狗狗</a></br>
<script>
alert(document.anchors.length);
</script>
</body>
</html>
弹出框值为3
![SouthEast 4][]
这个示例有个奇怪的地方,就是超链接里面必须添加name属性,document.anchors才能获取到超链接,否则document.anchors 拿到的集合为空集合。如果有知道的朋友,可以说一下原因。
document.forms
再看一个集合属性document.forms 获取所有的form表单的集合
<html>
<head>
<title>Attribute</title>
</head>
<body bgColor="#CCDDAA">
<form id="form1">
</form>
<form id="form2">
</form>
<script>
alert(document.forms.length);
</script>
</body>
</html>
弹出框值为2,示例中有两个form表单。
获取集合类属性中的单个对象方法
接着上面的代码,假如我们想要获取到第一个form表单的id属性值,该如何获取呢?
集合类属性的结果都是集合,都可以通过数组下标的方式来获取,
即
var forms = document.forms;
for (i=0; i<forms.length; i++){
alert(forms[i].id);
}
其次,我们断点下集合属性。
![SouthEast 5][]
可以看到其中的item() 方法,item方法传递的参数为对象在集合中的序号
将alert(forms\[i\].id); 修改为 alert(forms.item(i).id); 同样出效果。
基本上,集合属性通过这两种方式访问就可以了,如果开发中遇到更多的问题,想获取更多的访问方式,那请通过上面的断点的方式,查看具体有哪些操作方法,然后再想办法入手问题。
还没有评论,来说两句吧...