當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JavaScript:window.onload问题
生活随笔
收集整理的這篇文章主要介紹了
JavaScript:window.onload问题
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
前幾天做一個點(diǎn)擊按鈕,就實現(xiàn)切換圖片效果的小demo時,代碼看上去沒問題,就是達(dá)不到效果。讓我百思不得其解。
代碼如下:
<!DOCTYPE html> <html><head><meta charset="UTF-8"><title></title></head><body><img src="img/1.png"/><input type="button" id="btn" value="改變圖片" onclick="changePic()" /></body><script type="text/javascript">window.onload=function(){//1.獲取img標(biāo)簽var img=document.getElementsByTagName("img");//2.定義count來存對應(yīng)圖片---圖片名字分別為1,2,3,4var count=2;//3.切換圖片函數(shù)function changePic(){if(count<4){img[0].src="img/"+count+".png"; count++;}else if(count==4){img[0].src="img/"+count+".png";count=1;}}}</script> </html>一直以來,我們寫前端代碼時,第一件事就是寫window.onload的呀!為什么會出問題呢?
后來,上網(wǎng)去查,才得知是因為changePic()放在window.onload中就變成了一個局部函數(shù)了,不能實現(xiàn)在標(biāo)簽中的直接調(diào)用。
去掉window.onload就可以使用了。
代碼如下:
<!DOCTYPE html> <html><head><meta charset="UTF-8"><title></title></head><body><img src="img/1.png"/><input type="button" id="btn" value="改變圖片" onclick="changePic()" /></body><script type="text/javascript">//1.獲取img標(biāo)簽var img=document.getElementsByTagName("img");//2.定義count來存對應(yīng)圖片---圖片名字分別為1,2,3,4var count=2;//3.切換圖片函數(shù)function changePic(){if(count<4){img[0].src="img/"+count+".png"; count++;}else if(count==4){img[0].src="img/"+count+".png";count=1;}} </script> </html>如果你非要用window.onload,就使用–對象.函數(shù)–的方法
代碼如下:
<!DOCTYPE html> <html><head><meta charset="UTF-8"><title></title></head><body><img src="img/1.png"/><input type="button" id="btn" value="改變圖片" /></body><script type="text/javascript">window.onload=function(){//1.獲取img標(biāo)簽var img=document.getElementsByTagName("img");//2.定義count來存對應(yīng)圖片---圖片名字分別為1,2,3,4var count=2;//3.切換圖片函數(shù)document.getElementById("btn").onclick=function(){if(count<4){img[0].src="img/"+count+".png"; count++;}else if(count==4){img[0].src="img/"+count+".png";count=1;}}}</script> </html>總結(jié)
以上是生活随笔為你收集整理的JavaScript:window.onload问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java之反射--练习
- 下一篇: 前端开发工程师做些什么?