Jquery on image error not working on dynamic images?

后端 未结 2 1363
礼貌的吻别
礼貌的吻别 2020-12-01 13:59

I have the following js code,

 $(document).on(\"error\", \"img\", function () {
            alert(\'a\')
            this.src = ResolveUrl(\"~/images/tree-it         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 15:00

    I know, its an old question, but maybe someone is looking for a better solution:

    // The function to insert a fallback image
    var imgNotFound = function() {
        $(this).unbind("error").attr("src", "/path/to/fallback/img.jpg");
    };
    // Bind image error on document load
    $("img").error(imgNotFound);
    // Bind image error after ajax complete
    $(document).ajaxComplete(function(){
        $("img").error(imgNotFound);
    });
    

    This code attaches the error-event listener to the img tag on body load and after every ajax call.

提交回复
热议问题