在jQuery中调用.append()之后处理时序的正确方法

时间:2014-08-28 16:02:53

标签: javascript jquery timer append

我有一个动态生成的表,我使用.append()附加到页面。我知道这应该是瞬间的,但似乎不是。有没有办法或更好的方法来阻止代码执行,直到表格在屏幕上呈现?如果我清除缓存并加载页面,高亮显示div(用透明色覆盖表格)的大小/位置不正确。随后加载页面,它工作正常。这就是我的工作,但感觉很糟糕:

$('#insert-here').append(tableInsert);

//Even though .append() is "instant," this timeout is necessary to properly size the highlight divs the very first time the page loads.
setTimeout(function() {
    $('.highlight').each(function() {
        $(this).parent().css('position', 'relative');
        $(this).height($(this).prev().find('.info-row').height());
        $(this).width($(this).prev().find('.info-row').width());
        $(this).offset($(this).prev().find('.info-row').offset());
    });
}, 125);

1 个答案:

答案 0 :(得分:1)

append返回之前,元素被添加到DOM中。你所看到的是他们尚未渲染的事实,所以他们的高度/宽度尚未确定。

根据我的经验,确定他们已经呈现的唯一方法是让JavaScript线程回放到浏览器,完全按照您的方式完成(但延迟可以短得多;我通常使用{ {1}})。