search

Home  >  Q&A  >  body text

javascript - How does JQuery add an onload event to the newly created img tag and call it automatically.

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;
}
阿神阿神2774 days ago659

reply all(3)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-17 10:08:31

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

    reply
    0
  • 高洛峰

    高洛峰2017-05-17 10:08:31

    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;
    };

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-17 10:08:31

    reply
    0
  • Cancelreply