Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

106
Vistas
El bloque desaparece si no hay ninguna imagen en él

¡Toda salud y felicidad! Un script escrito que debe iterar a través de todas las imágenes, si las imágenes no se cargaron, entonces el script debe ocultar el bloque principal en la clase .Parent_block , es decir, tengo 3 bloques, hay una imagen en el bloque central, pero no en los otros dos, lo que significa que deberían tener propiedad display:none

Pero hice algo mal. ¿Dónde cometí un error?

 let parent_block = document.querySelectorAll('.Parent_block'); let image_b = document.querySelectorAll('.Child_Img'); image_b.forEach(function(){ if(image_b.onerror){ for(let parent_block of hide){ hide.style.display = 'none'; } } })
 .Parent_block{ width:30%; margin:0; padding:0; margin-left:10px; margin-top:10px; border:1px solid black; display:inline-block; height:250px; } img{ height:inherit; width:100%;
 <figure class="Parent_block"> <!-- ***** this block should disappear ***** =( --> <img class="Child_Img" src=""> <figcaption class ="Img_text">1</figcaption> </figure> <figure class="Parent_block"> <img class="Child_Img" src="https://i.ibb.co/kyXhZmB/photo-2021-11-18-14-40-18.jpg"> <figcaption class ="Img_text">2</figcaption> </figure> <figure class="Parent_block"> <!-- ***** and this one too ***** =( --> <img class="Child_Img" src=""> <figcaption class ="Img_text">3</figcaption> </figure>

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

  • en error - leer más

  • más cercano - leer más

 let parent_block = document.querySelectorAll('.Parent_block'); let image_b = document.querySelectorAll('.Child_Img'); image_b.forEach(function(image){ // check if any error (if image doesn't load in our case) image.addEventListener("error",()=>{ // find closest class name and hide it image.closest(".Parent_block").style.display = "none"; }) })
 .Parent_block{ width:30%; margin:0; padding:0; margin-left:10px; margin-top:10px; border:1px solid black; display:inline-block; height:250px; } img{ height:inherit; width:100%;
 <figure class="Parent_block"> <!-- ***** this block should disappear ***** =( --> <img class="Child_Img" src=""> <figcaption class ="Img_text">1</figcaption> </figure> <figure class="Parent_block"> <img class="Child_Img" src="https://i.ibb.co/kyXhZmB/photo-2021-11-18-14-40-18.jpg"> <figcaption class ="Img_text">2</figcaption> </figure> <figure class="Parent_block"> <!-- ***** and this one too ***** =( --> <img class="Child_Img" src=""> <figcaption class ="Img_text">3</figcaption> </figure>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Hay algunos problemas con el guión.

  • Está ejecutando image_b.forEach y dentro de eso está intentando acceder a image_b.onerror . Esto no funcionará ya que image_b es una matriz.
  • onerror es un evento y no una propiedad. Por lo tanto, no se puede acceder de esta manera.
  • La sintaxis for(let parent_block of hide) es incorrecta.

Código fijo

Lógica

  • Selecciona todos los elementos con el nombre de clase Child_Img .
  • Recorra los elementos y registre un evento de onerror en cada elemento de la lista que seleccionamos con el nombre de clase Child_Img .
  • En el evento de error, busque el elemento más cercano con el nombre de clase Parent_block y ocúltelo.

violín de trabajo

 let image_b = document.querySelectorAll('.Child_Img'); image_b.forEach(function (img) { img.onerror = function(image) { img.closest(".Parent_block").style.display = 'none'; } })
 .Parent_block { width: 30%; margin: 0; padding: 0; margin-left: 10px; margin-top: 10px; border: 1px solid black; display: inline-block; height: 250px; } img { height: inherit; width: 100%; }
 <figure class="Parent_block"> <!-- ***** this block should disappear ***** =( --> <img class="Child_Img" src=""> <figcaption class="Img_text">1</figcaption> </figure> <figure class="Parent_block"> <img class="Child_Img" src="https://i.ibb.co/kyXhZmB/photo-2021-11-18-14-40-18.jpg"> <figcaption class="Img_text">2</figcaption> </figure> <figure class="Parent_block"> <!-- ***** and this one too ***** =( --> <img class="Child_Img" src=""> <figcaption class="Img_text">3</figcaption> </figure>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Hay una serie de problemas con su script.
Algunos ejemplos:

  1. onerror no debe verificarse con if , sino con event listener.
  2. forEach necesita un argumento, no ha proporcionado ninguno.
  3. Debe agregar .onerror al argumento de foreach , y no directamente a image_b
  4. No hay ninguna variable declarada como hide en su secuencia de comandos. Supongo que tenías la intención for (let hide of parent_block)
  5. Asumiendo que arregló todo hasta el #4, el bucle ejecuta hide.style.display = 'none' para todo parent_block, y no solo para los que incluyen las imágenes con errores.

Lo siguiente debería funcionar:

 let parent_block = document.querySelectorAll('.Parent_block'); let image_b = document.querySelectorAll('.Child_Img'); image_b.forEach(function (cur_image) { cur_image.onerror = function () { for(let block of parent_block){ if(block.contains(cur_image) ){ block.style.display = 'none'; } } } })

Pero el ciclo sobre parent_block no es necesario, solo puede encontrar el ancestro relevante de cur_image :

 // let parent_block = document.querySelectorAll('.Parent_block'); let image_b = document.querySelectorAll('.Child_Img'); image_b.forEach(function (cur_image) { cur_image.onerror = function () { let hide = cur_image.closest('.Parent_block') hide.style.display = 'none'; } })

Tenga en cuenta que ni siquiera es necesario ejecutar document.querySelectorAll('.Parent_block') nunca más.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda