search
HomeWeb Front-endFront-end Q&AUse javascript to determine whether the image exists_If it does not exist, display the code of the default image

In a website or application, sometimes we need to display an image, but we are not sure whether the image exists or whether it has been deleted on the server. At this time, if the image is displayed directly, errors may occur. In order to solve this problem, we can use Javascript code to determine whether the image exists, and display a default image if the image does not exist. This article will introduce how to use Javascript to implement this function.

First, we need to wrap the image to be displayed in a div or img tag, and set a custom attribute src-real in the tag to store the real path of the image. The code is as follows:

<div class="image-container">
  <img  class="image" src="" src-real="path/to/image.jpg" alt="Use javascript to determine whether the image exists_If it does not exist, display the code of the default image" >
</div>

Next, we can use Javascript to determine whether the image exists. Using the onload and onerror events of the Image object, the corresponding event processing function can be triggered when the image loading is completed or fails. We can set the src attribute of the image to the real path src-real in the loading completion event onload to display the image; set the src attribute of the image to the path of the default image in the loading failure event onerror, as shown below:

// 获取所有要判断的图片节点
const images = document.querySelectorAll('.image')

// 循环遍历每个图片节点
images.forEach(image => {

  // 创建一个新的Image对象
  const img = new Image()

  // 加载完成,显示实际图片
  img.onload = () => {
    image.src = image.getAttribute('src-real')
  }

  // 加载失败,显示默认图片
  img.onerror = () => {
    image.src = 'path/to/default-image.jpg'
  }

  // 设置Image对象的src属性并加载图片
  img.src = image.getAttribute('src-real')
})

In the above code, we first obtain all the image nodes to be judged through the querySelectorAll method, and loop through each image node. Then, we created a new Image object and set its onload and onerror event handlers. When the image is loaded, the onload event is triggered. We can get the real path src-real of the image through the getAttribute method, and assign the path to the src attribute of the image node to display the actual image; when the image fails to load, When the onerror event is triggered, we can set the src attribute of the image node to the path of the default image to display the default image.

Finally, we need to set the style of the default image in CSS so that when the image fails to load, the correct default image can be displayed. The code is as follows:

.image {
  width: 300px;
  height: 200px;
  background-color: #ddd;
}

.image[src*="default"] {
  background-image: url('path/to/default-image.jpg');
  background-size: cover;
  background-repeat: no-repeat;
}

In the above code, we first set the width, height and background color of the image. Then, we use the CSS attribute selector [src*="default"] to select all image nodes that contain "default" in the src attribute, and then set the background image of the image node to the path of the default image, so as to display the default Picture effect.

To sum up, we can use Javascript code to determine whether the image exists, and display the default image when the image does not exist. This can enhance the user experience and reduce error situations caused by image loading failures.

The above is the detailed content of Use javascript to determine whether the image exists_If it does not exist, display the code of the default image. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
CSS: Can I use multiple IDs in the same DOM?CSS: Can I use multiple IDs in the same DOM?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

The Aims of HTML5: Creating a More Powerful and Accessible WebThe Aims of HTML5: Creating a More Powerful and Accessible WebMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

Significant Goals of HTML5: Enhancing Web Development and User ExperienceSignificant Goals of HTML5: Enhancing Web Development and User ExperienceMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

HTML5: Is it secure?HTML5: Is it secure?May 14, 2025 am 12:15 AM

HTML5isnotinherentlyinsecure,butitsfeaturescanleadtosecurityrisksifmisusedorimproperlyimplemented.1)Usethesandboxattributeiniframestocontrolembeddedcontentandpreventvulnerabilitieslikeclickjacking.2)AvoidstoringsensitivedatainWebStorageduetoitsaccess

HTML5 goals in comparison with older HTML versionsHTML5 goals in comparison with older HTML versionsMay 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.