Jquery图像错误不适用于动态图像? [英] Jquery on image error not working on dynamic images?

查看:86
本文介绍了Jquery图像错误不适用于动态图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下js代码,

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

此事件未被触发。我确定有很多破损的图像

This event is not triggered. I am sure there are lot of broken images

推荐答案

问题是你不能使用事件委托用于文档对象上的错误事件,因为与其他事件不同(例如 onclick ), onerror 事件未被冒泡到文档对象。

The problem is that you can't use event delegation for the error event on the document object, because unlike other events (such as onclick), the onerror event isn't being bubbled to the document object.

使用普通事件绑定:

$('img').on("error", function () {
    this.src = ResolveUrl("~/images/tree-item.png");
});




  • PS - 这仅适用于已经存在的图像执行此命令时的DOM。

  • 要处理动态添加的图像,需要将此事件附加到您添加到DOM的每个图像。这是一个例子:

    To handle dynamically added images as well, you need to attach this event to every image you add to the DOM. Here's an example:

    function handleError() {
        this.src = ResolveUrl("~/images/tree-item.png");
    }
    
    // Bind the event to the existing images on the DOM when the document is ready
    $(document).ready(function () {
        $('img').on("error", handleError);
    }
    
    // An example for a function that adds images dynamically
    function addImage(imgSource, destination) {
        var newImg = $("img").attr("src", imgSource)
                             .on("error", handleError);
    
        $(destination).append(newImg);
    }
    

    这篇关于Jquery图像错误不适用于动态图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆