Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

255
Views
eliminar la imagen y su contenedor si la imagen está rota

Solo estoy tratando de eliminar la imagen y su título en caso de que la imagen no se cargue o se rompa usando html o JavaScript. ¿Cuál es la mejor y más fácil manera de hacerlo?

 <?php include("../includes/db.php"); // ../ means go to parent directory $query='SELECT * FROM `table` WHERE tag NOT IN("news") ORDER BY `id` DESC LIMIT 0,5'; $run=mysqli_query($conn,$query); while($row=mysqli_fetch_array($run)){ $img=$row['src']; $title=$row['title']; ?> <table class='mobileTable'> <tr> <td><img src='<?php echo $img ?>' onerror='imgError(this)' /></td></tr> <tr> <td class='mobMidTitle'><?php echo $title ?></td></tr>//i want to remove this title as well </table> <?php } ?> <script> function imgError(image) { image.onerror = ""; image.src = "http://localhost/domain/images/error.jpg"; document.getElementById('tit').style.display='none'; return true; }</script>

el código anterior obtendrá 5 imágenes de la base de datos y con javascript puedo cambiar la imagen a error.jpg pero quiero eliminar tanto la imagen como el título solo de la imagen fallida.

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Puede lograr esto de una de dos maneras:

Utilice la función removeChild ( asumiendo que desea eliminar los elementos y no ocultarlos ):

 function imgError(image) { // Get image row var imageRow = image.parentNode.parentNode; // Get image label row var imageLabel = imageRow.nextElementSibling; // Get table element of that image row and remove imageLabel imageRow.parentNode.removeChild(imageLabel); // Get table element of that image row and remove img element imageRow.parentNode.removeChild(imageRow); }

O, en cambio, puede ocultar sus elementos usando la propiedad .style.visibility de los elementos de imagen y etiqueta:

 function imgError(image) { // Get image row var imageRow = image.parentNode.parentNode; // Get image label row var imageLabel = imageRow.nextElementSibling; // Hide imageLabel imageRow.style.visibility = 'hidden'; // Hide imageRow imageLabel.style.visibility = 'hidden'; }
about 4 years ago · Santiago Trujillo Report

0

¿Qué tal este JQuery javascipt ( https://jquery.com ) para ocultar cualquier imagen que no se haya podido cargar?

 $("img").error(function() { $(this).hide(); });

o, si desea ocultar su contenedor, puede hacer esto:

 $("img").error(function() { $(this).parent().hide(); });

o si realmente desea eliminar la imagen o el contenedor, use remove() en lugar de hide() .

También puede mostrar su propia imagen de error:

 $("img").error(function() { $(this).attr("src","error.png"); });

El código ha sido probado y funciona.

Puede hacerlo más específico seleccionando solo aquellas imágenes que desea ocultar o eliminar. Cambie $("img") a $(".hideOnError") y use la clase hideOnError en aquellas imágenes que desea ocultar o eliminar. Se pueden tomar diferentes acciones como replaceOnError . También puede aplicar esto a otros elementos cargables.

En tu caso concreto tienes dos elementos que quieres eliminar cuando falla una imagen. La mejor manera de hacerlo es asociar el título con la imagen a través de atributos:

 <table class='mobileTable'> <tr><td><img id='image1' src='<?php echo $img ?>'></td></tr> <tr><td id='image1title' class='mobMidTitle'><?php echo $title ?></td></tr> </table>

Como puede ver, la identificación de la imagen aquí es image1 y la celda de la tabla que contiene el título tiene id image1title . Para eliminar la imagen y el título por error, dejando intacta la estructura de la tabla, haga lo siguiente:

 $("img").error(function() { var id = $(this).attr('id'); // get id of image $(this).remove(); // remove image $("#"+id+"title").empty(); // remove title });
about 4 years ago · Santiago Trujillo Report

0

bueno, hay múltiples enfoques para hacer esto:

aquí, asumo que desea usar Pure javascript -no jquery- y mantener la jerarquía original del documento DOM.

 <table class='mobileTable'> <tr> <td><img src='path/to/broken/image.jpg' onerror='imgError(this)' /></td></tr> <tr> <td class='mobMidTitle'>some title</td></tr> </table> <script> function imgError(image) { // this will step up to get the parent of the image's parent var imgParent = image.parentElement.parentElement; // this will get the next sibling of the image grandpa var nextSib = imgParent.nextElementSibling; // reset it's html to empty nextSib.innerHTML = ''; image.onerror = ""; image.src = "http://localhost/domain/images/error.jpg"; return true; } </script>

otro enfoque más fácil es agregar una nueva ID a su TD de título y luego eliminarla usando javascript de la siguiente manera:

 /* here we've added id='mobMidTitle' */ <td class='mobMidTitle' id='mobMidTitle' >some title</td> <script> function imgError(image) { image.onerror = ""; image.src = "http://localhost/domain/images/error.jpg"; document.getElementById('mobMidTitle').style.display = 'none'; // ^^^^^^^^^^^ return true; } </script>
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!