JQuery的。对()事件处理程序使用动态加载的图像图像、加载、事件、程序

2023-09-10 14:18:18 作者:妳已決定走開

我的页面是动态通过Ajax响应生成。

My pages are generating dynamically by ajax response.

每个响应具有指定ID的 IMG 元素。我需要他们的时候装在褪色。

Each response has an img element with specified id. I need them to fade in when loaded.

.load() .bi​​nd('负荷')时,页面加载的第一次工作正常。但不工作的肯定下一个响应。

.load() and .bind('load') works fine when page is loaded for first time. But not working in next response for sure.

$('#my_img').load(function(){
   $(this).hide().fadeIn('slow');
});

所以,我需要使用。对()事件处理程序。但是,不能正常工作。

So i need to use .on() event handler. But doesn't work.

$('body').on('load','#my_img',function(){
   $(this).hide().fadeIn('slow');
});

请注意:这不是一个缓存的问题。 IMG SRC还具有一个随机查询字符串

Note: This is not a cache issue. Img src also has a random query string.

推荐答案

的onload 该事件不会冒泡,所以你不能委派它。但是,如果你不需要支持IE8<,你可以捕捉事件,而不是将适用于任何动态IMG:

onload event doesn't bubble, so you cannot delegate it. But, if you don't need to support IE8<, you can capture event instead which will work for any dynamic img:

document.body.addEventListener(
    'load',
    function(event){
        var elm = event.target;
        if( elm.id === 'my_img'){ // or any other filtering condition
            // do some stuff
        }
    },
    true // Capture event
);

-demo -