最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - create img with onerror attribute using jQuery - Stack Overflow

programmeradmin2浏览0评论

I am creating some images in my page. When I write <img src=somesrc, onerror=othersrc></img>, it works fine.

But when I create image using jQuery it fails:

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

How do I solve this?

I am creating some images in my page. When I write <img src=somesrc, onerror=othersrc></img>, it works fine.

But when I create image using jQuery it fails:

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

How do I solve this?

Share Improve this question asked Jun 18, 2012 at 1:09 onemachonemach 4,3257 gold badges36 silver badges55 bronze badges 2
  • 1 But when I create image using jQuery it fails How does it fail? What exactly fails? – Felix Kling Commented Jun 18, 2012 at 1:33
  • @FelixKling the onerror code does not get executed and so the default image does not get loaded. – onemach Commented Jun 18, 2012 at 3:34
Add a ment  | 

2 Answers 2

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

Works fine. Link to jsFiddle plus extra words

发布评论

评论列表(0)

  1. 暂无评论