JS set img Tag src resource cannot find an alternative picture (via IMG property settings)

Source: Internet
Author: User

In the front-end page design of the site, to consider the existence of IMG image resources, if the IMG src Image resource does not exist or display, you need to display the default picture. How do we do that?

One, the error event of monitoring document

Document.addeventlistener ("Error", Function (e) {varElem =E.target; if(elem.tagName.toLowerCase () = = ='img') {        varNOTFOUNDIMGSRT = $ (elem). attr ("notfoundsrc"); if(NOTFOUNDIMGSRT) {$.Get(NOTFOUNDIMGSRT,NULL, function (response, status, XHR) {if(Xhr.status = = = $) Elem.src=notfoundimgsrt;        }); }    }}, true);

The IMG onerror event is not bubbling, so we have to manually write the code and listen for the error event of the document. If the target of the current error event is an IMG tag, locate the Notfoundsrc property of the IMG tag and use AJAX to determine whether the default picture exists for the current site, and if the default picture exists, assign it the SRC attribute of the IMG.

Second, set the Notfoundsrc property of the IMG tag

  <img src="xxxxx" alt="  notfoundsrc="images/ Imgnotfound.png"/>

As can be seen by code, XXXXX is not a path to a real picture resource, so:

1, the IMG tag will trigger its error event;

2, because we have customized a document error monitoring event, then the document will capture the error event that IMG sent;

3. Execute the logic of the error event.

JS settings img Tag src Resource cannot find an alternative picture (via IMG property settings)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.