當(dāng)前位置:
首頁(yè) >
前端技术
> javascript
>内容正文
javascript
JavaScript:window.onload问题
生活随笔
收集整理的這篇文章主要介紹了
JavaScript:window.onload问题
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
前幾天做一個(gè)點(diǎn)擊按鈕,就實(shí)現(xiàn)切換圖片效果的小demo時(shí),代碼看上去沒(méi)問(wèn)題,就是達(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來(lái)存對(duì)應(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>一直以來(lái),我們寫前端代碼時(shí),第一件事就是寫window.onload的呀!為什么會(huì)出問(wèn)題呢?
后來(lái),上網(wǎng)去查,才得知是因?yàn)閏hangePic()放在window.onload中就變成了一個(gè)局部函數(shù)了,不能實(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來(lái)存對(duì)應(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,就使用–對(duì)象.函數(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來(lái)存對(duì)應(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问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Java之反射--练习
- 下一篇: 前端开发工程师做些什么?