我得到一些html并插入它与.html()
,之后我试图得到一个新插入的元素与.width()
(其中有一个CSS规则)之一的宽度。然而,有时 - 宽度没有拿起,并返回为0.jQuery:为什么在使用.html()插入元素后,.width()有时会返回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%:(
你能告诉它与返回0,确切的代码?另外,哪些浏览器? – alex 2011-05-25 23:35:52
元素内是否有图像?你还在用WebKit进行测试吗? – alex 2011-05-25 23:36:50
如果所讨论的元素是图像,则只要图像尚未完成加载,就会返回零值... – 2011-05-25 23:37:01