设定页面有一个img对象,命名为img1.
<img name=img1>
测试document.images["img1"]与document.img1是否指向同一对象。
代码如下:
<html>
<body>
<img name=img1 src="" border=0 width=200 height=150>
<script language="JavaScript" type="text/javaScript">
var myImages=new Array("usa.jpg","canada.jpg","jamaica.jpg","mexico.jpg");
var imgIndex=prompt("Enter a number from 0 to 3","");
//document.images[0].src=myImages[imgIndex];
//document.images["img1"].src=myImages[imgIndex];
document.img1.src=myImages[imgIndex];
</script>
</body>
</html>
测试结果:
document.images[0].src和document.images["img1"].src与document.img1.src
执行相同操作。
总结:
对象img的引用可以使用如下几种方式:
1.使用document对象的images[]属性。如:document.images[0]来引用页面第一个img对象。也可以声明一个变量用于引用images[]数组中的某一个img对象,以使代码更加容易阅读。
var myImage1=document.images[0];
变量myImage1将包含一个对images[]数组中索引为0的img对象的引用。此后,在代码中,可以使用myImage1来代替document.images[0],二者的效果完全相同。
2.使用html中标签<img>的名称来访问images[]数组中的对应的img对象。如:<img name=img1>;document.images["img1"]来访问img对象。
3.document对象中直接使用对象img的名称。如:document.img1来引用img对象。