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

javascript - OnError not shown the default image - Stack Overflow

programmeradmin6浏览0评论

I'm trying to display a default image when the other specified in src doesn't exists, so I did:

<img src=".././uploads/images/avatar/' + user.id + '.png" onerror="this.src='+"assets/img/default-avatar.png"+'"></div>';

the problem is that I still get the broken thumbnail. Strange thing is that: if I switch the src, so I place assets/img/default-avatar.png in the src all works well, any idea?

I'm trying to display a default image when the other specified in src doesn't exists, so I did:

<img src=".././uploads/images/avatar/' + user.id + '.png" onerror="this.src='+"assets/img/default-avatar.png"+'"></div>';

the problem is that I still get the broken thumbnail. Strange thing is that: if I switch the src, so I place assets/img/default-avatar.png in the src all works well, any idea?

Share Improve this question asked Feb 12, 2019 at 12:01 sfarzososfarzoso 1,6407 gold badges31 silver badges83 bronze badges 4
  • 1 what these + sign means? – Maheer Ali Commented Feb 12, 2019 at 12:02
  • 1 @MaheerAli concatenate the string path – sfarzoso Commented Feb 12, 2019 at 12:02
  • Are you writing this in a JS file? – Nick Parsons Commented Feb 12, 2019 at 12:03
  • @NickParsons yes, I need to concatenate it because it start with ' – sfarzoso Commented Feb 12, 2019 at 12:04
Add a ment  | 

2 Answers 2

Reset to default 3

Make sure that quotes matching:

'<img src=".././uploads/images/avatar/' + user.id + '.png" onerror="this.src='+"assets/img/default-avatar.png"+'"></div>';

Or, more readable, use the power of template strings:

`<img src=".././uploads/images/avatar/${user.id}.png" onerror="this.src='${"assets/img/default-avatar.png"}'"></div>`;

Put like this,

onerror="javascript:this.src='/assets/img/default-avatar.png'"

OR

onerror="this.src='/assets/img/default-avatar.png'"

发布评论

评论列表(0)

  1. 暂无评论