今天在学习《Javascript DOM编程艺术》时遇到了一个问题:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Index</title>
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script src="script/index.js"></script>
</head>
<body>
<h1>Snapshots</h1>
<ul>
<li><a href="images/park.jpg" title="park" onclick="showPic(this); return false;">Park</a></li>
<li><a href="images/sea.jpg" title="sea" onclick="showPic(this); return false;">Sea</a></li>
<li><a href="images/woods.jpg" title="woods" onclick="showPic(this); return false;">Woods</a></li>
<li><a href="images/tower.jpg" title="tower" onclick="showPic(this);return false;">Tower</a></li>
</ul>
<img id="placeholder" class="placeholder" src="images/placeholder.jpg" alt="my img">
</body>
</html>
index.js
function showPic(whichPic) {
var source = whichPic.getAttribute("href");
var placeholder = document.getElementById("placeholder");
placeholder.setAttribute("src",source);
}
目标实现效果是点击链接,会将下面占位符图片的地址替换成点击链接的地址并显示在原来的位置。
在Javascript中return false;一般是是用来取消默认动作的,但是发现代码中的return false;并没有起作用
尝试了几种办法,下面这个可以用:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Index</title>
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script src="script/index.js"></script>
</head>
<body>
<h1>Snapshots</h1>
<!--改成return showPic()-->
<ul>
<li><a href="images/park.jpg" title="park" onclick="return showPic(this);">Park</a></li>
<li><a href="images/sea.jpg" title="sea" onclick="return showPic(this);">Sea</a></li>
<li><a href="images/woods.jpg" title="woods" onclick="return showPic(this);">Woods</a></li>
<li><a href="images/tower.jpg" title="tower" onclick="return showPic(this);">Tower</a></li>
</ul>
<img id="placeholder" class="placeholder" src="images/placeholder.jpg" alt="my img">
</body>
</html>
index.js
function showPic(whichPic) {
var source = whichPic.getAttribute("href");
var placeholder = document.getElementById("placeholder");
placeholder.setAttribute("src",source);
//return在这里返回
return false;
}