最近在学习Javascript编程的艺术,其中有一章节说的是图片库的问题,实现点击链接,在网页不跳转的情况下,更换下方的图片的效果。
现在有一个问题,当我点击按钮,网页会跳转,我也在匿名函数里写了点击返回false的,为什么还会跳转呢?求助,求助,谢谢!
以下是代码:
<!DOCTYPE html>
<html>
<head>
<title>Snapshots</title>
<meta charset="utf-8">
</head>
<body>
<h1>Snapshots</h1>
<ul id="imageGallery">
<li><a href="images/1.png" title="A red house">Red house</a></li>
<li><a href="images/2.png" title="A blue house">blue house</a></li>
<li><a href="images/3.png" title="A white house">white house</a></li>
<li><a href="images/4.png" title="A brown house">brown house</a></li>
<img id="placeholder" src="images/placeholder.png" alt="占位符">
<p id="description">choose an image.</p>
</ul>
<script>
function prepareGallery() {
if (!document.getElementsByTagName) {return false;}
if (!document.getElementById) {return false;}
if (!document.getElementById("imageGallery")) {return false;}
var gallery = document.getElementById("imageGallery");
var links = gallery.getElementsByTagName("a");
for (var i=0; i<links.length; i++){
links[i].onclick = function(){
showPic(this);
return false; //屏蔽游览器跳转的行为
}
}
}
function showPic(whichpic){
if (!document.getElementById("placeholder")) {return false;}
var source = whichpic.getAttribute("href");
var placeholder = document.getElementById("placeholder");
placeholder.setAttribute("src",source);
if (document.getElementById("description")){
var get_title = whichpic.getAttribute("title");
var description = document.getElementById("description");
description.firstChild.nodeValue = get_title;
}
return true;
}
</script>
</body>
</html>
执行
prepareGallery
方法: