簡體   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