jQuery image load callback

≡放荡痞女 提交于 2019-12-01 02:11:09

问题


Dynamically adding an image to the page after load then user interaction and am having trouble firing a function after that image has completely loaded. I figured that using jQuery's .load() method would be fine.. but according my console and a bunch of documenting .log business it's never executed. See below.. thank you!

$('body')
    .append('<img id="ad" src="img/ad.jpg" alt="Advertising Network" />')
    .load(function(){
        console.log('ad load complete');
        $('#submit').click();
    });

UPDATE:

To clarify, this is after both document and window load.


回答1:


In your code .load() is related to the body because of chaining.

Change the code to:

var img = $('<img id="ad" src="img/ad.jpg" alt="Advertising Network" />');
img.load(function(){
    console.log('ad load complete');
    $('#submit').click();
});

$('body').append(img);

and it should work (http://jsfiddle.net/zerkms/f7epb/)




回答2:


The append function returns the containing element, not the one that was appended, so you are binding your function to the body's load and not to the img.

I suggest using appendTo, like so:

$('<img id="ad" src="img/ad.jpg" alt="Advertising Network" />')
.load(function(){
    console.log('ad load complete');
    $('#submit').click();
})
.appendTo($('body'));


来源:https://stackoverflow.com/questions/10790226/jquery-image-load-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!