问题描述:首先代码通过点击链接实时改变预占的图片和文本,之后想把HTML中的Js脚本分离出来,但分离之后并未实现想要的结果,另一个链接点开后也是。请各位大神帮忙看看是什么问题,在此先谢过!
代码如下:
<!doctype html>
<html lang="en">
<head>
<mate charset="utf-8">
<title>Image Gallery</title>
<link type="text/css" rel="stylesheet" href="layout.css">
</head>
<body>
<h1>Snapshots</h1>
<nav>
<ul id="imagegallery">
<li><a href="images/duorou.jpg" title="A fireworks display">Fireworks</a></li>
<li><a href="images/jinx.jpg" title="A cup of black coffee">Coffee</a></li>
<li><a href="images/jinx_pic.jpg" title="A red,red rose">Rose</a></li>
<li><a href="images/wandou.jpg" title="The famous clock">Big Ben</a></li>
</ul>
</nav>
<img id="placeholder" src="images/wandou.jpg" art="my image gallery">
<p id="description">Choose an image.</p>
<a href="www.example.com" class="popup" title="web">Firefox</a>
<script type="text/javascript" src="showPic.js"></script>
</body>
</html>
JavaScript脚本:
window.onload = prepareGallery;
function showPic(whichpic) {
var source = whichpic.getAttribute("href");
var placeholder = document.getElementById("placeholder");
placeholder.setAttribute("src", source);
var text = whichpic.getAttribute("title");
var description = document.getElementById("description");
description.firstChild.nodeValue = text;
}
function prepareGallery() {
if (!document.getElementById || !document.getElementsByTagName) {
return false;
}
if (!document.getElementById("imagegallery")) {
return false;
}
var gallery = document.getElementById("imagegallery");
var links = gallery.getElementsTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].onclick = function () {
showPic(this);
return false;
}
}
}
/*function countBodyChildren(){
var body_element=document.getElementsByTagName("body")[0];
alert(body_element.childNodes.length);
}
window.onload=countBodyChildren;*/
function popUp(winURL) {
window.open(winURL, "popup", "width=320,height=480");
}
window.onload = prepareLinks;
function prepareLinks() {
var link = document.getElementsByTagName("a");
for (var i = 0; i < link.length; i++) {
if (link[i].getAttribute("class") == "popup";) {
link[i].onclick = function () {
popUp(this.getAttribute("href");
return false;
}
}
}
}
prepareLinks
函数中的分号都放在if
判断中了。window.onload
进行了覆盖,所以prepareGallery
完全没用。popup
class的a标签挂载了事件,所以其他的a标签连事件都没挂上,自然不会触发你希望走的代码。