Use Javascript to determine whether an image exists. If the image does not exist, the default image code is displayed.

Source: Internet
Author: User

The onerror event of the image object is used to determine whether to change the src of the image object to the URL of the default image.
<P> first case: The image exists and is displayed normally </p> <p> second case: The image does not exist. The default image is displayed. </p>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]

The following is a js judgment
Use javascript to determine whether a specified image file exists:
For example, judge whether the image address exists.
If the image does not exist, the image will be detected again several seconds later. If the address is valid, the system will prompt that the address is valid.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function IsExist (url)
{
X = new ActiveXObject ("Microsoft. XMLHTTP ")
X. open ("HEAD", url, false)
X. send ()
Return x. status = 200
}
Alert (IsExist ("http://www.bkjia.com/uploads/allimg/131015/14542G5b-1.gif "))
</Script>

If the image exists, true is returned.
Copy codeThe Code is as follows:
<SCRIPT language = "javascript">
Var xmlhttp = new ActiveXObject ("Msxml2.XMLHTTP ");
Xmlhttp. Open ("GET", "http://www.bkjia.com/uploads/allimg/131015/14542G5b-1.gif", false );
Xmlhttp. Send ();
Alert (xmlhttp. responseText );
</SCRIPT>

If the image exists, GIF89aX is returned.
Copy codeThe Code is as follows:


Because the image does not exist, the returned image does not exist!

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.