JavaScript初学与inserAfter函数
function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { oldonload(); func(); } } }
上面这段函数是加载后执行函数,无论有多少个函数,只需要在js文件末尾添加addLoadEvent()就可以加载后执行函数了。一句的事!!
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Image Gallery</title> </head> <body> <h1>Snapshots</h1> <ul> <li> <a href="image/bone7.jpg" onclick="showPic(this); return false;" title="a famous dota player">bone7</a> <li> <a href="image/Forever-07.jpg" onclick="showPic(this); return false;" title="a old man">Forever-07</a> </li> <li> <a href="image/HuiYuanAi.jpg" onclick="showPic(this); return false;" title="a beautiful girl">HuiYuanAi</a> </li> <li> <a href="image/GeYOU.jpg" onclick="showPic(this); return false;" title="a funny movie star">GeYOU</a> </li> </ul> <img id="KeNan" src="image/KeNan.jpg" alt="my image gallery"/> <script type="text/javascript" src="scripts/showPic.js"></script> </body> </html>
function showPic(whichpic) { var source=whichpic.getAttribute("href"); var KeNan=document.getElementById("KeNan"); KeNan.setAttribute("src",source); }
加入childNodes,为什么先加载一次网页(360安全浏览器)显示数字8,点击确定后又弹出alert显示9呢?然后就没有alert了。不懂。
function showPic(whichpic) { var source= whichpic.getAttribute("href"); var KeNan= document.getElementById("KeNan"); KeNan.setAttribute("src",source); } function countBodyChildren() { var body_element= document.getElementsByTagName("body")[0]; alert(body_element.childNodes.length); window.onload= countBodyChildren; } countBodyChildren();
编写insertAfter函数
function insertAfter(newElement,targetElement){ var parent=targetElement.parentNode; if(parent.lastChild==targetElement){ parent.appendChild(newElement); }else{ parent.insertBefore(newElement,targetElement.nextSibling); } }