[英]How to know if all images are added dynamically loaded? javascript, jquery
[英]check if dynamically added images is loaded
我正在創建一個簡單的 html 頁面,其中一個圖像被動態添加到 div 中,如下所示
$(".step3html").html('<img class="mobimg thumbnail" src="img/'+keys+'">');
我想在圖像完全加載后調整容器的大小(它是絕對容器)。 那么如何檢查附加的圖像是否已加載並調用一些函數,我將根據整個容器寬度運行調整大小函數。
我在附加圖像后立即嘗試了下面的代碼,它似乎沒有觸發。
$(".mobimg").on('load', function() {
alert("das");
});
下面的代碼有效。
$(".step3html").html('<img class="mobimg thumbnail" src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150">');
$(".mobimg").on('load', function() {
alert("das");
});
試試這個小提琴。
https://jsfiddle.net/pparas/whhjtwpp/
你可能有不同的問題。 您是否檢查過控制台中keys
的值?
編輯
這是一個工作小提琴。
您應該從新創建的元素img
。 此代碼有效。
<button id="btn">button</button>
<div id="div"></div>
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
$('<img class="mobimg thumbnail" src="/images/hat22.jpg?a='
+ Math.random()/*ensure load from server*/ + '" />').load(function () {
console.log('load');
$('#div').empty().width($(this).prop('naturalWidth') + 10).append(this);
});
});
});
</script>
你可以寫:
$('.mobimg').load(function(){
//your code
});
當所有元素和子元素完全加載時,.load .load()
被觸發。
典型的模式是創建一個圖像,綁定加載處理程序,然后設置src
。
添加一個事件監聽器,讓圖像通過 onload 宣布自己
<img class="mobimg thumbnail" onload='loadedImageFunction(this.id)' src="https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150">
然后編寫javascript函數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.