Use JavaScript to determine if a picture exists, does not exist the code to display the default picture _javascript tips

Source: Internet
Author: User

Use the OnError event of an Image object to determine that an error replaces the URL of the image object's SRC as the default picture.

<p> first case: Picture exists, normal display </p> <p> second case: Picture does not exist, show default picture </p>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]


here is the decision through JS
Use JavaScript to determine whether the specified picture file exists:
If you judge This picture address exists.
If it does not exist, the picture is probed in a few seconds, and the prompt address is valid if the address is valid
Copy Code code 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.jb51.net/logos.gif"))
</script>

The picture is present returns true above
Copy Code code as follows:

<script language= "JavaScript" >
var xmlhttp = new ActiveXObject ("Msxml2.xmlhttp");
xmlHTTP. Open ("Get", "Http://www.jb51.net/logos.gif", false);
xmlHTTP. Send ();
alert (Xmlhttp.responsetext);
</SCRIPT>

Picture exists returns GIF89AX
Copy Code code as follows:



Return the picture does not exist because the picture does not exist!

Related Article

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.