setTimeout 0 妙用

why?

<div id="test">

</div>

<script>
    document.getElementById('test').innerHtml = "<div id='er'></div>";
    document.getElementById('er').innerHtml = 'test';  
</script>


在脚本中,第一步在test容器中,插入子容器er。接着第二步在子容器er中,写入文字。这里,可能第一步完成后,页面dom树并没有立即得到更新,可能在第二步中并不能成功获取到er容器,造成错误

how?怎么样避免这种错误呢?

setTimeout(function(){},0);

表示0毫秒后,立刻执行此函数。0 毫秒的起点是:文档稳定后开始计时。

what?

上述脚本应该这样写:

<script>
    document.getElementById('test').innerHtml = "<div id='er'></div>";
    setTimeout(function(){
        document.getElementById('er').innerHtml = 'test';  
        },0);
</script>



案例1 :

iscroll 中,当容器内容发生更新时,需要调用refresh 函数,官方文档是这样调用的

ajax('page.php', onCompletion);

function onCompletion () {
	// Here modify the DOM in any way, eg: by adding LIs to the scroller UL
	
	setTimeout(function () {
		myScroll.refresh();
	}, 0);
};

setTimeout  0 在此时的作用是,当更新的内容在文档流中稳定后,再使用refresh 计算更新后的容器大小



参考:

http://cubiq.org/iscroll-4

http://www.jb51.net/article/17193.htm



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值