这是我的html
<a href="index.php"><img id="testimg" src="images/logo.png"/></a>
这是我的javascript
function getW(){
var theImg = document.getElementById('testimg');
return theImg;
}
theImg = getW();
if (theImg.width > 119){
document.write(theImg.width);
}
现在,当我使用这个脚本时,它会输出 img 宽度
但是当我使用这个脚本时
function getW(){
var theImg = document.getElementsByTagName("img");
return theImg;
}
theImg = getW();
if (theImg.width > 119){
document.write(theImg.width);
}
它不输出任何东西。有什么区别,为什么第二个脚本会起作用?
谢谢!
最佳答案
因为 getElementsByTagName()
返回一组多个元素(注意元素)。您需要使用 [0]
来获得第一个匹配项。
另一方面,id
应该始终是唯一的,因此 getElementById()
返回对单个元素的引用。
关于javascript - 文档.getElementsByTagName ("img");与 document.getElementById ('testimg' 相比);,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5813317/