javascript - How does JQuery add an onload event to the newly created img tag and call it automatically.
阿神
阿神 2017-05-17 10:06:31
0
3
657

This is what it looks like when you first enter the page: After the webpage is loaded, the target image will be automatically called. If it is not found, use the backup image (onload event noImg() method in JS). The problem now is, if in the search box After entering the keyword, click search. After the search results are displayed on the web page, the onload method is no longer called. I added onload: "noImg()" to it, but it didn't work. How to break it? Ask God for enlightenment~

When the page was just loaded, it looked like this:

Then click search and it will look like this:

There is a search box above. After entering keywords in the search box, an Ajax asynchronous request is called, and the data sent back is repopulated into the page:

    for(i in data){
        /* $('<p />').attr("src","img/2017329/2.png").css().appendTo(jqTag); */
        
        var pTag = $('<p/>');
        var h4Tag = $('<h4/>').html("模型名称:"+data[i].modelName);
        var imgTag = $('<img/>').attr({
            alt:"...",
            src:data[i].picFileUrl,
            
            onload:"noImg()"
        });

This is the js method that was available from the beginning:
/ Use backup images when the web page images are unrealistic /

function noImg(){
         var img = event.srcElement;
         img.src = "images/img.jpg";
         img.onerror = null;
}
阿神
阿神

闭关修行中......

reply all(3)
曾经蜡笔没有小新

var img = new Image();
img.src = '';
img.onload= function(){}

小葫芦

http://stackoverflow.com/ques...
Note, onload事件应当在图片srcbefore assignment.
Reference code:

var imgLoad = function (url) {
   var img = new Image();
   if (img.complete) {
       callback();
   } else {
       img.onload = function () {
           callback();
           img.onload = null;
       };
   };
  img.src = url;
};
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template