我是JS新手,並且正在閱讀Javascript Dom,我試圖找出我書中的一個例子!爲什麼我getElementById時會得到空值?
這裏是我的html代碼
<!DOCTYPE html>
<html lang ="en">
<head>
<meta charset="utf-8" />
<title>Image Gallery</title>
</head>
<body>
<script type = "text/javascript" src="showPic.js"></script>
<h1>Snapshots</h1>
<ul id = "image">
<li>
<a href="images/fall.JPG" title = "water display"> Fall</a>
</li>
<li>
<a href="images/sun.JPG" title = "sunshine"> Sunshine</a>
</li>
<li>
<a href="images/tree.jpg" title = "tree"> Green</a>
</li>
<li>
<a href="images/yellow.JPG" title = "yellow sun">Filter</a>
</li>
</ul>
<img id = "placeholeder" src="images/rise.jpg" alt = "my image gallery"/>
<p id="description"> Choose an image</p>
</body>
</html>
這裏是我的JavaScript代碼
function showPic(whichPic) {
var source = whichPic.getAttribute("href");
var placeholder = document.getElementById("placeholeder");
placeholder.setAttribute("src", source);
description.firstChild.nodeValue = text;
}
var text = whichPic.getAttribute("title");
var description = document.getElementById("description");
function perpareGallery() {
var gallery = document.getElementById("image");
var links = gallery.getElementsByTagName("a");
for(var i = 0 ; i<links.length; i++) {
links[i].onclick = function() {
showPic(this);
return false;
}
}
}
我的代碼didnt正從ID =圖像什麼。我檢查了很多次,不知道什麼是錯誤的......
可能需要document.ready – rjustin
'showPic'函數的關閉'}'在哪裏?現在'perpareGallery'看起來像是在'showPic'函數中。 – llama
整個代碼? – soft87