jQuery:为什么在.html()插入元素后,.width()有时返回0?

我得到一些html并插入.html(),之后我试图获取一个新插入的元素的宽度..((它有一个CSS规则).但是有时 – 宽度不会被拾取,并返回0.

是因为JS在新创建的元素和它们的CSS中运行“前进”吗?我已经尝试用.html(‘…’)链接,find(‘…’).width(),但它有时不起作用.原因是什么,有没有办法解决

编辑:按人气需求,示例:

/* ajax.response is:
    <div class="Boxes">
        <div class="Box width-A">test 1</div>
        <div class="Box width-B">test 2</div>
        <div class="Box width-C">test 3</div>
    </div> */

var BoxOutput = $('.BoxOutput'); /* .BoxOutput is already on the page */
BoxOutput.html(ajax.response);

// make width of ".Boxes" equal to the sum of all ".Box"

var BoxWidth = 0;
$('.Box',BoxOutput).each(function(i) {
    BoxWidth += $(this).width(); /* this is where sometimes width returns 0 */
});
$('.Boxes',BoxOutput).css('width',BoxWidth);

我的原始代码太长/难以复制/粘贴,但这是一个简单的确切的事情我在做(对不起,如果有一个愚蠢的错误,在那里我太迟了:P).从ajax获取html后,将其放入div中,我想要获取每个框的宽度(因为它可能会有所不同),然后使用该宽度.再次,90%的时间,宽度正确返回.当有时宽度为0时是10%

解决方法

取决于什么浏览器.偶尔,我发现有些事情会与JavaScript运行时的同步渲染预期一起破裂,我需要在下一个勾选中获得结果.

我会尝试:

$(elem).html(data);
setTimeout(function(){
    // Get the width here
},0);

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...