繁体   English   中英

在jQuery中创建图像并在加载后添加到DOM

[英]Creating an image in jQuery and adding to DOM after load

我有一个创建图像对象的函数。 我给图像一个src,然后我添加一个加载函数,一旦加载就将图像添加到DOM。 它的工作原理除了它总是向页面添加2个图像实例,我无法弄清楚原因。 有人能告诉我为什么这会在我的页面上添加两个图像吗?

var img = new Image();

$(img).load(function () {               
    $('#imageContainter').append(this);
    $(this).fadeIn();
})              
.error(function () {
    // notify the user that the image could not be loaded
})              
.attr('src', '' + _filename);   

“_filename”是源路径,“imageContainer”是我加载图像的div。

任何帮助将不胜感激。

$(new Image()).attr('src', '' + _filename).appendTo($('#imageContainter')).fadeIn();

然后,如果'错误'部分很重要,你可以检查src或其他东西。

如果你没有提供任何淡入淡出时间,我还建议使用show()而不是fadeIn()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM