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