JavaScript 簡單應用,javascript應用
JavaScript 簡單應用
一:簡介
此筆記是對《JavaScript權威指南》第4章內容的概括、重點的記錄。不是重現書本執行個體。書中大部分執行個體放在github上、有興趣的也可以看這本書或者github上代碼。github地址會放在JavaScript目錄中。
二:JavaScript應用步驟
1. 編寫JavaScript指令碼
2. 在頁面中引用:
a)可以直接在頁面中使用<script>標籤將JavaScript相關內容放入其中。
b)可以將指令碼放入一個或者多個檔案結尾為js的檔案中、在需要使用的頁面中引入。
三:執行個體簡述
網頁中有多個連結、不點擊任何連結時、頁面下方的顯示位置會顯示一張預設圖片和預設說明、當點擊某個具體連結時將下方顯示位置的預設圖片替換成連結定向到的圖片、同時將連結的說明內容顯示在指定位置。
四:執行個體實現關鍵點
1. 擷取a連結的herf和title屬性。
2. 為所有連結添加單擊事件。
3. 阻止連結預設行為。
2. 修改預設圖片標籤的src和說明標籤內的常值內容。
五:相關方法與解決方式
1.阻止a預設行為:
<li><a onclick="switchPicture(this); return false" href="../picture/chenhong.jpg" title="Chen hong">Chen hong</a></li>
2.相關方法
function switchPicture (whichPicture) {var source = whichPicture.href;var placeholder = document.getElementById('placeholder');placeholder.setAttribute('src', source);document.getElementById('description').firstChild.nodeValue = whichPicture.getAttribute('title');}
六:補充
效果:
showPicture.js:
function switchPicture (whichPicture) {var source = whichPicture.href;var placeholder = document.getElementById('placeholder');placeholder.setAttribute('src', source);document.getElementById('description').firstChild.nodeValue = whichPicture.getAttribute('title');}/* function countBodyChildren () { alert(document.getElementsByTagName('body')[0].childNodes.length); } window.onload = countBodyChildren;*/
showPicture.html:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Show Picture</title><script src="../js/showPicture.js" ></script><link rel="stylesheet" href="../style/showPicture.css"></head><body><h1>Snapshots</h1><ul><li><a onclick="switchPicture(this); return false" href="../picture/chenhong.jpg" title="Chen hong">Chen hong</a></li><li><a onclick="switchPicture(this); return false" href="../picture/liuyan.jpg" title="Liu Yan">Liu Yan</a></li><li><a onclick="switchPicture(this); return false" href="../picture/liuyifei.jpg" title="Liu Yi Fei">Liu Yi Fei</a></li><li><a onclick="switchPicture(this); return false" href="../picture/shishi.jpg" title="Liu Shi Shi">Liu Shi Shi</a></li></ul><img src="../picture/benchi.jpg" alt="my image gallery" id="placeholder"><p id="description">Choose one picture!</p></body></html>
showPicture.css:
body {font-family: "Helvetica", "Arial", serif;color: #333;background-color: #ccc;margin: 1em 10%;}h1 {color: #333;background-color: transparent;}a {color: #c60;background-color: transparent;font-weight: bold;text-decoration: none;}ul {padding: 0;}li {float: left;padding: 1em;list-style: none;}img {display: block;clear: both;}