使用 jQuery 创建具有 onerror 属性的 img

create img with onerror attribute using jQuery

本文关键字:属性 img onerror jQuery 创建 使用      更新时间:2023-09-26

我正在我的页面中创建一些图像。当我写<img src=somesrc, onerror=othersrc></img>时,它工作正常。

但是当我使用 jQuery 创建图像时,它失败了:

jQuery('<img />', {
    onerror: "javascript: this.src='some_default_image_source'", 
    src: 'image_source'}).appendTo("#container");

我该如何解决这个问题?

jQuery('<img />').error(function() {
    this.src = 'some_default_image_source';
}).attr('src', 'image_source').appendTo("#container");

工作正常。链接到jsFiddle加上额外的单词