我在学习js的基础知识的时候,按照书上的例子打以下代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
<style>
pre{border:medium double black;}
</style>
</head>
<body>
<pre id="results"></pre>
<img src="img/lemon.png" alt="lemon" id="lemon">
<p>
There are lots of different kinds of fruit - there are over 500
varieties of banana alone.By the time we add the
countless types of apples,oranges,and other well-known fruit,we are faced
with thousands of choices.
</p>
<img id="apple" src="img/apple.png" alt="apple">
<p>
One of the most interesting aspects of fruit is the
variety avaliable in each country.I live near London,in an area which is
known for its apples.
</p>
<img src="img/banana-small.png" id="banana" alt="small banana" >
<script>
var resultsElement = document.getElementById("results");
var elems = document["apple"];
if (elems.namedItem){
for (var i = 0; i < elems.length; i++){
resultsElement.innerHTML += "Image Element: "+elems[i].id + "\n";
}
} else{
resultsElement.innerHTML += "Src for element is: "+elems.src + "\n";
}
</script>
</body>
</html>
但是一直没有结果,浏览器显示elems是undefined,是
var elems = document["apple"];
这句话出了问题吗?
下面是书上关于这种方法的解释,但是我不知道为啥我没有成功获得id为apple的元素,而用其他方法,如document.images.namedItem("apple")等方法是可以获取的