jQuery:为什么在使用 .html() 插入元素后 .width() 有时会返回 0?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6132141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: Why does .width() sometimes return 0 after inserting elements with .html()?
提问by Jon Derring
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.
我正在获取一些 html 并用 插入它.html()
,之后我试图用.width()
(它有一个 CSS 规则)获取新插入元素之一的宽度。但是有时- 宽度没有被拾取,并返回为 0。
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?
是因为 JS 运行在新创建的元素及其 css 之前吗?我试过链接,.html('...').find('...').width()
但有时仍然不起作用。原因是什么,是否有解决方法?
Edit: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);
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 :(
我的原始代码太长/太丑,无法复制/粘贴,但这是我正在做的一个简化的确切事情(对不起,如果某处有一个愚蠢的错误,我现在为时已晚:P)。从ajax获取html后,将其放入div中,我想获取每个框的宽度(因为它可能不同),然后使用该宽度。同样,在 90% 的情况下,宽度会正确返回。有时宽度为 0 时就是 10% :(
回答by Josh
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.
要看什么浏览器。有时,我发现某些内容会与 javascript 运行时的同步呈现期望不同,我需要在下一个滴答声中获得结果。
I'd try:
我会尝试:
$(elem).html(data);
setTimeout(function(){
// Get the width here
},0);
回答by nick
jQuery will return a zero width if the element is not visible. For example, I was having the same issue with an item being inserted onto a hidden form tab. Temporarily assigning it to the body, where it was visible, I was able to determine the width:
如果元素不可见,jQuery 将返回零宽度。例如,我在将项目插入隐藏表单选项卡时遇到了同样的问题。暂时将它分配给可见的身体,我能够确定宽度:
$("body").append(el); // First assign it to the body so that it's visible
var width = el.width(); // The width will now be correct
wrapper.append(el); // Now place the element where you want it.
One caveat is that if the element inherits different styling when assigned to the body then the width may not be correct.
一个警告是,如果元素在分配给主体时继承了不同的样式,则宽度可能不正确。
回答by Mircea Stanciu
We found out that document.ready was not good enough so 300ms worked well:
我们发现 document.ready 不够好,所以 300ms 效果很好:
setTimeout(function() {
resizeHeightOfMyDiv();
$(window).on("resize", function() {
resizeHeightOfMyDiv();
});
}, 300);
回答by Sajjad Shirazy
// ...
$('.box', boxOutput).each(function(i) {
//boxWidth += $(this).width(); /* this is where sometimes width returns 0 */
boxWidth += this..getBoundingClientRect().width;
});
//...
回答by BlackLight
If the element is an image, then the
width()
andheight()
methods should be accessed on the.load()
jQuery handler;If the element is a DOM subtree, then they should be accessed on the
.ready()
handler.
如果元素是图像,则应该在jQuery 处理程序上访问
width()
和height()
方法.load()
;如果元素是 DOM 子树,则应该在
.ready()
处理程序上访问它们。
The reason is that you can't rely on what jQuery reports to be the size of the element until the element has actually been loaded.
原因是在元素实际加载之前,您不能依赖 jQuery 报告的元素大小。
回答by Claudiu
Not sure 100% but I think that your problem is that the code called outside the function where you attach the elements doesn't recognize the newly created elements. A quick example:
不确定 100%,但我认为您的问题是在附加元素的函数外部调用的代码无法识别新创建的元素。一个简单的例子:
<div id="container">
</div>
<script>
$(document).ready(function() {
$('#container).html('<p style="width:200px">Lorem ipsum</p>');
alert($('#container p').width()); // alerts 0
$('#container p').html('Lorem ipsum dolor sit amet'); // if content doesn't change, it's clearly a problem of jquery not being able to bind the functions to your new elements
});
</script>
If you can tell us what you're doing exactly we'll surely find a solution.
如果您能准确地告诉我们您在做什么,我们一定会找到解决方案。
LATER EDIT
稍后编辑
Now that you posted code, I can actually help. You need to run this code:
现在您发布了代码,我实际上可以提供帮助。您需要运行此代码:
$('.box', boxOutput).each(function(i) {
boxWidth += $(this).width(); /* this is where sometimes width returns 0 */
});
in the function in your ajax response function. Example:
在 ajax 响应函数中的函数中。例子:
$.get('script.php', function(data) {
$('#elem').html(data);
// your code for width()
});
Hope this helps.
希望这可以帮助。