javascript - 请问为什么这个补零函数为什么要放window.onload外面?
问题描述
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>Document</title></head><body style='background: black;color: #fff;font-size: 58px;'> <img src='https://www.haobala.com/wenda/img/0.png' /> <img src='https://www.haobala.com/wenda/img/0.png' /> : <img src='https://www.haobala.com/wenda/img/0.png' /> <img src='https://www.haobala.com/wenda/img/0.png' /> : <img src='https://www.haobala.com/wenda/img/0.png' /> <img src='https://www.haobala.com/wenda/img/0.png' /> <script>function bul(n){ if(n<10) {return '0'+n; } else {return ''+n; }}window.onload=function(){ var aImg = document.getElementsByTagName(’img’); var tell; tell=setInterval(function(){var myDate = new Date();var str = bul(myDate.getHours())+bul(myDate.getMinutes())+bul(myDate.getSeconds());for(var i=0;i<aImg.length;i++){ aImg[i].src = 'https://www.haobala.com/wenda/img/'+str[i]+'.png';}},500)tell();} </script></body></html>
小白不太明白其中的道理,求各位前辈详细解释一下。感谢。
问题解答
回答1:作用域问题、放在外面、无论你是window.onload、window.onunload 都可以使用
放在window.onload的代码只是为了保证页面加载完毕、保证节点确实存在、不会选不到节点
而你那种对数字操作的方法、没有节点操作、放在里外都可以
回答2:window.onload 事件是页面完全加载完的时候执行
$(function(){ }) 是等页面上的标签加载完了就执行
回答3:里面外面都可以,放外面可以共用,放里面只能在onload事件内部用。
相关文章:
1. dockerfile - [docker build image失败- npm install]2. 关docker hub上有些镜像的tag被标记““This image has vulnerabilities””3. boot2docker无法启动4. docker gitlab 如何git clone?5. docker网络端口映射,没有方便点的操作方法么?6. docker-compose中volumes的问题7. docker不显示端口映射呢?8. dockerfile - 我用docker build的时候出现下边问题 麻烦帮我看一下9. docker images显示的镜像过多,狗眼被亮瞎了,怎么办?10. html5 - node静态资源服务器设置了Cache-Control,但浏览器从来不走304
![dockerfile - [docker build image失败- npm install]](http://www.haobala.com/attached/image/news/202311/1028105a80.png)
网公网安备