微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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);

原文地址:https://www.jb51.cc/jquery/179706.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐