JavaScript:window.onload问题

xiaoxiao2021-02-28  112

前几天做一个点击按钮,就实现切换图片效果的小demo时,代码看上去没问题,就是达不到效果。让我百思不得其解。

代码如下:

<!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标签 var img=document.getElementsByTagName("img"); //2.定义count来存对应图片---图片名字分别为1,2,3,4 var count=2; //3.切换图片函数 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的呀!为什么会出问题呢?

后来,上网去查,才得知是因为changePic()放在window.onload中就变成了一个局部函数了,不能实现在标签中的直接调用。

去掉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标签 var img=document.getElementsByTagName("img"); //2.定义count来存对应图片---图片名字分别为1,2,3,4 var count=2; //3.切换图片函数 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,就使用–对象.函数–的方法

代码如下:

<!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标签 var img=document.getElementsByTagName("img"); //2.定义count来存对应图片---图片名字分别为1,2,3,4 var count=2; //3.切换图片函数 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>
转载请注明原文地址: https://www.6miu.com/read-40133.html

最新回复(0)