jQuery 附加后没有图像尺寸
我有以下代码,它循环获取表中的所有图像,然后将它们附加到#featured
,然后将其附加到#wrapper
。问题是在所有内容都附加到 #wrapper
后,图像没有尺寸,因此没有一个显示。这就像图像的宽度和高度都是 0px 一样。我如何克服这个尺寸问题。
var featured = '<div id="featured"></div>';
$('#imageTable tbody tr td img').each(function(){
$(featured).append('<img src='+$(this).attr("src")+' />');
});
$(featured).appendTo('#wrapper');
我试图通过这样做来解决这个问题
$(featured).load(function(){
$(this).appendTo('#wrapper');
});
但这不起作用。
I have the following code, which loops to get all images in a table then appends them to #featured
which is then appended to #wrapper
. The problem is after everything is appended to #wrapper
, images have no dimensions and for that reason non of them show. It's like having 0px width and height for images. How do i overcome this size issue.
var featured = '<div id="featured"></div>';
$('#imageTable tbody tr td img').each(function(){
$(featured).append('<img src='+$(this).attr("src")+' />');
});
$(featured).appendTo('#wrapper');
I tried to solve this problem by doing
$(featured).load(function(){
$(this).appendTo('#wrapper');
});
But that doesn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题是,每次您说
$(featured)
时,您都在创建一个全新的 jQuery 对象;然后你对它做了一些事情,然后把它——以及你对它所做的——扔掉。结果是您最终将一个空的附加到
#wrapper
:图像不会没有尺寸,它们只是根本不存在。创建一个 jQuery 对象并继续使用该对象:
演示: http://jsfiddle.net/ambigously/PXVG2/< /a>
一遍又一遍地执行
$(x).append(...)
将会起作用,前提是x
已经存在于 DOM 中;你的不是这样的。如果您首先将其附加到
#wrapper
并且#wrapper
在 DOM 中,那么如果您使用#featured
而不是HTML:演示: http://jsfiddle.net/ambigously/vPyy6/
后一种方法相当不错虽然很浪费,但它在每次
.each
迭代中创建一个新的 jQuery 对象。第一种方法要好得多。Your problem is that every time you say
$(featured)
, you're creating a brand new jQuery object; then you do something to it and throw it — and what you did to it — away. The result is that you end up appending an empty<div id="featured">
to#wrapper
: the images don't come out with no dimensions, they're just not there at all.Create one jQuery object and keep using that one object:
Demo: http://jsfiddle.net/ambiguous/PXVG2/
Doing
$(x).append(...)
over and over again will work provided thatx
is something that is already in the DOM; your<div id="featured">
isn't such a thing. If you appended it to#wrapper
first and#wrapper
was in the DOM, then it would work okay if you used#featured
instead of the HTML:Demo: http://jsfiddle.net/ambiguous/vPyy6/
This latter approach is rather wasteful though, it creates a new jQuery object on each
.each
iteration. The first approach is much better.