Javascript入門學習第五篇 js函數
更新時間:2008年07月06日 10:00:53 作者:
上篇文章講了js中對象和數組的一些方法。
這章我們先說說函數,然后來點實戰(zhàn)。
6,實戰(zhàn):
編寫一個javascript圖片館:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=gbk" />
<title>Image Gallery</title>
<script type="text/javascript" >
function showPic(whichpic) {
var source = whichpic.getAttribute("href"); //獲取當前點擊的元素的屬性href的值
var placeholder = document.getElementById("placeholder"); //獲取目標
placeholder.setAttribute("src",source);
/*
設置目標的屬性src。從而達到改變圖片。
setAttribute完成了2部操作:即先創(chuàng)建屬性,然后賦值。如果屬性存在,則覆蓋屬性的值。
當然我們可以用 placeholder.src = source;
不過,還是建議大家使用setAttribute(),它是1級dom,
他可以對文檔中的任何一個元素的任何一個屬性做出修改。
另外他的移植性更好。
*/
var text = whichpic.getAttribute("title");
//獲取當前點擊的元素的屬性title的值
var description = document.getElementById("description");//獲取目標
description.firstChild.nodeValue = text;
/*
或者使用
description.childNodes[0].nodeValue = text;
*/
}
</script>
</head>
<body>
<h1>javascript 圖片館</h1>
<!--
在a標簽上加事件我們要注意,避免要他跳轉。
解決方法:函數返回false; 事件認為鏈接沒有被點擊。
當然這種情況是在href的值有用的情況下。
如果href的值是javascript:void(0);也可以不跳轉。
-->
<ul>
<li>
<a href="images/fireworks.jpg" title="test1" onclick="showPic(this); return false;">test1</a>
</li>
<li>
<a href="images/coffee.jpg" title="test2" onclick="showPic(this); return false;">test2</a>
</li>
<li>
<a href="images/rose.jpg" title="test3" onclick="showPic(this); return false;">test3</a>
</li>
<li>
<a href="images/bigben.jpg" title="test3" onclick="showPic(this); return false;">test4</a>
</li>
</ul>
<img id="placeholder" src="images/placeholder.gif" alt="my image gallery" />
<p id="description">選擇圖片.</p>
</body>
</html>
看了這個例子,也許你會納悶,我怎么就看不懂呢?
如果是這樣,那么你的納悶是對的。呵呵。
看不懂就看不懂吧。 先把看不懂的 拿筆記住, 后面幾章我們講 學習 DOM編程。
到時候 一切不懂 都會被化解。。。。。。
總節(jié):
這章沒說什么重大的東西,浪費了大家時間了。請原諒我。。。
不過下幾章,相信大家都比較感興趣。。。保密。^_^。
如果還有不懂,可以google 搜索資料.
相關文章
this.clientWidth和this.offsetWidth兩個有什么不同
this.clientWidth和this.offsetWidth兩個有什么不同...2006-10-10