js定时器内写的函数不能在外部调用

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
function zr(n)//将数字转换成字符串并在一位数前添‘0’
{
 if(n<10)
 {
  return '0'+n;
 }
 else
 {
  return ''+n;  //前面加空字符能保证它返回的一定是个字符串而不是数字
 } 
}
window.onload=function()
{
 var oDiv1=document.getElementById('div1');
 var oDiv2=document.getElementById('div2');
 var aImg1=oDiv1.getElementsByTagName('img');
 var aImg2=oDiv2.getElementsByTagName('img');
 
 function clock()
 {
  var oDate = new Date();
  var str1=zr(oDate.getFullYear())+zr(oDate.getMonth()+1)+zr(oDate.getDate());//获取系统日期,并转换成字符串
  var str2=zr(oDate.getHours())+zr(oDate.getMinutes())+zr(oDate.getSeconds());//获取系统时间,并转换成字符串
  
  for(var i=0; i<aImg1.length; i++)//更改img下的图片
  {
   aImg1[i].src='img09/'+str1.charAt(i)+'.png';//此处用charAt能做到全兼容,如用str1[i]部分浏览器不兼容
  }
  
  for(var i=0; i<aImg2.length; i++)//更改img下的图片
  {
   aImg2[i].src='img09/'+str2.charAt(i)+'.png';
  }
 }
 setInterval(clock,500);//这里我们在定时器里面调用clock函数,如果我们偷懒将clock函数直接写在setInterval里面,下面我们将无法调用clock函数
 clock();//由于定时器不会在打开网页的时候立即执行定时器里面的代码,我们需要在此处调用clock函数,让它立即执行一次,防止刷新网页的时候出现全‘0’的现象(由于我的img标签的src默认值是0.png(数字‘0’))
}
</script>
</head>

<body style="background:#000; font-size:100px; color:#FFF">
<div id="div1">
 <img src="img09/0.png" />
    <img src="img09/0.png" />
    <img src="img09/0.png" />
    <img src="img09/0.png" />
    年
    <img src="img09/0.png" />
    <img src="img09/0.png" />
    月
    <img src="img09/0.png" />
    <img src="img09/0.png" />
    日
</div>
<div id="div2">
 <img src="img09/0.png" />
    <img src="img09/0.png" />
    :
    <img src="img09/0.png" />
    <img src="img09/0.png" />
    :
    <img src="img09/0.png" />
    <img src="img09/0.png" />
</div>
</body>
</html>

如果我们将定时器写成这样将无法在下面调用clock函数

setInterval(function clock()
 {
  var oDate = new Date();
  var str1=zr(oDate.getFullYear())+zr(oDate.getMonth()+1)+zr(oDate.getDate());
  var str2=zr(oDate.getHours())+zr(oDate.getMinutes())+zr(oDate.getSeconds());
  
  for(var i=0; i<aImg1.length; i++)
  {
   aImg1[i].src='img09/'+str1.charAt(i)+'.png';
  }
  
  for(var i=0; i<aImg2.length; i++)
  {
   aImg2[i].src='img09/'+str2.charAt(i)+'.png';
  }
 }
 ,500);
 clock();//这里无法调用clock函数
}


转载于:https://my.oschina.net/u/2602502/blog/602165

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值