jQuery:为什么在用.html()插入元素后,.width()有时有时返回0? [英] jQuery: Why does .width() sometimes return 0 after inserting elements with .html()?
问题描述
我得到一些html并用.html()
插入它,之后我尝试用.width()
(具有CSS规则)获取新插入的元素之一的宽度.但是有时-宽度没有被拾取,并返回为0.
I am getting some html and inserting it with .html()
, after which I am trying to get the width of one of newly inserted elements with .width()
(which has a CSS rule). However sometimes - the width is not picked up, and is returned as 0.
是因为JS对新创建的元素及其CSS进行超前"处理吗?我尝试使用.html('...').find('...').width()
进行链接,但有时仍然无法正常工作.是什么原因,有什么解决方法?
Is it because JS runs "ahead" of newly created elements and their css? I have tried chaining with .html('...').find('...').width()
but it still sometimes does not work. What's the reason and is there a work around?
根据流行的需求,例如:
By popular demand, EXAMPLE:
/* 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%:(
My original code is too long/ugly to copy/paste, but this is a simplified exact thing I am doing (Sorry if there's a silly mistake somewhere, it's too late where I am :P). After getting html back from ajax, putting it into a div, I want to get width of each box (because it might be different), and then use that width. Again, 90% of the time, the width is returned correctly. It's those 10% when sometimes width is 0 :(
推荐答案
取决于哪种浏览器.有时候,我发现某些东西会与javascript运行时的同步渲染期望值相冲突,因此我需要在下一个刻度上得到结果.
Depends on what browser. Occasionally I find something will break with the synchronous rendering expectations of the javascript runtime and I'll need to get the result on the next tick.
我会尝试:
$(elem).html(data);
setTimeout(function(){
// Get the width here
},0);
这篇关于jQuery:为什么在用.html()插入元素后,.width()有时有时返回0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!