<!DOCTYPE html><html><head><meta charset="utf-8"><title>Image Gallery</title><style type="text/css">*{margin: 0;padding: 0;}body{width: 960px;margin: 30px auto;background: rgba(134,205,80,0.2);}ul{display: inline-block;width: 100%;padding: 20px;}li{list-style: none;width: 20%;float: left;}a{text-decoration: none;color: #000;}img{width: 640px;height: 400px;}p{padding: 20px 0;}</style><script type="text/javascript">function addLoadEvent(func){var oldonload=window.onload;if(typeof window.onload!='function'){window.onload=func;}else{window.onload=function(){oldonload();func();}}}addLoadEvent(prepareGallery);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 text=whichpic.getAttribute('title')?whichpic.getAttribute('title'):'';var description=document.getElementById('description');description.firstChild.nodeValue = text;}return true;}function prepareGallery(){if(!document.getElementsByTagName) return false;if(!document.getElementById) return false;if(!document.getElementById('gallery')) return false;var gallery=document.getElementById('gallery');var link=gallery.getElementsByTagName('a');for(var i=0;i<link.length;i++){link[i].onclick=function(){return !showPic(this);}}}</script></head><body><h1>Image Gallery</h1><ul id="gallery"><li><a href="img/2.jpg" title="image2" target="_blank">image2</a></li><li><a href="img/3.jpg" title="image3">image3</a></li><li><a href="img/4.jpg" title="image4">image4</a></li><li><a href="img/5.jpg" title="image5">image5</a></li></ul><img src="img/2.jpg" id="placeholder" alt="my image gallery"><p id="description">image gallery</p></body></html>關(guān)于addLoadEvent? ??addLoadEvent(prepareGallery);這一操作處window.onload涉及到兩個函數(shù),一個是prepareGallery,一個是showPic,但為什么只有addLoadEvent(prepareGallery);沒有addLoadEvent(showPic);呢?另外問一下,JS的執(zhí)行順序是怎樣的呢?是不是先把所有的函數(shù)加載完畢。那這樣的話,沒有addLoadEvent(showPic);shoePic函數(shù)里的doucument.getElementById等操作應(yīng)該獲取不到,為什么會正常運行呢?如果在addLoadEvent(prepareGallery);后面加上addLoadEvent(showPic);代碼依然可以正常運行,但是會顯示index.html:60 Uncaught TypeError: Cannot read property 'getAttribute' of undefined? ? at showPic (index.html:60)? ? at window.onload (index.html:48)檢查了一下也沒有寫錯什么字母單詞、標(biāo)點符號,也沒漏掉括號為什么會有錯誤麻煩大神解釋一下這三個問題(圖片麻煩修改后測試)
JS addLoadEvent()
sherryliu
2017-12-20 17:08:18