src放在上面的话,可能会因为加载太快,导致onload执行不了
所以,onload在上面,src在下面
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <style> #txt1 {300px;} #img1 {height:300px;} </style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script type="text/javascript"> window.onload=function () { var oTxt=document.getElementById('txt1'); var oBtn=document.getElementById('btn1'); var oImg=document.getElementById('img1'); oBtn.onclick=function () { var oNewImg=new Image(); oNewImg.onload=function () { oImg.src=this.src; }; oNewImg.onerror=function () { alert('图片有问题,加载失败'); }; oNewImg.src=oTxt.value; //src放在上面的话,可能会因为加载太快,导致onload执行不了 //所以,onload在上面,src在下面 }; }; </script> </head> <body> <input id="txt1" type="text" /> <input id="btn1" type="button" value="加载" /><br /> <img id="img1" onload="alert('完成');" /> </body> </html>