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

228
Views
¿Cómo hacer que se muestren diferentes imágenes al hacer clic en un botón de opción usando JavaScript?

He estado tratando durante días de resolver esto. Necesito hacer clic en un botón de radio y cambiar la imagen. Por ejemplo, si hago clic en el botón de radio del puente Golden Gate, necesito que cambie la imagen a la imagen del puente. Hasta ahora solo puedo hacer que haga clic en la imagen y luego la imagen cambia, pero eso no es lo que quiero hacer. He probado de muchas maneras diferentes y nada funciona. Soy nuevo en JavaScript.

 <!DOCTYPE html> <html> <body> <!--Statue of Liberty image--> <img id="statue" onclick="changeImage()" src= 'https://www.history.com/.image/ar_4:3%2Cc_fill%2Ccs_srgb%2Cfl_progressive%2Cq_auto:good%2Cw_1 200/MTY1MTc1MTk3ODI0MDAxNjA5/topic-statue-of-liberty-gettyimages-960610006-promo.jpg' width="300"> <p>Click the picture to change image.</p> <script> //Functon that changes mage when clicking on the image function changeImage() { var image = document.getElementById('statue'); if (image.src.match("statue")) { image.src= 'https://www.history.com/.image/ar_4:3%2Cc_fill%2Ccs_srgb%2Cfl_progressive%2Cq_auto:good%2Cw_1200/MTY1MTc3MjE0MzExMDgxNTQ1/topic-golden-gate-bridge-gettyimages-177770941.jpg'; } else if (image.src.match("bridge")) { image.src = "https://media-cldnry.s-nbcnews.com/image/upload/newscms/2020_26/3392557/200625-mount-rushmore-al-0708.jpg"; } } </script> <!-- Radio buttons--> <form> <input type="radio" id = "statue-button" name = "landmark" checked value="statue"onClick= ('toggleImage')>Statue of Liberty<br> <input type="radio" id = "bridge-button" name="landmark" value="bridge">Golden Gate Bridge<br> <input type="radio" id = "rushmore-button" name="landmark" value="rushmore">Mount Rushmore<br> </form> </body> </html>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Hay algunas cosas que debe corregir para que su código funcione como se espera.

 <input type="radio" id = "statue-button" name = "landmark" checked value="statue"onClick= ('toggleImage')>Statue of Liberty<br>

debe ser cambiado a

 <input type="radio" id="statue-button" name="landmark" checked value="statue" onClick="changeImage('statue')">Statue of Liberty<br>

Para que los espacios estén en los lugares correctos y el atributo onClick esté entre comillas.

Luego, dentro de la función changeImage() , debe verificar el parámetro (en mi ejemplo, llamado value ) simplemente por comparación. El método de match está diseñado para usarse con expresiones regulares y no es necesario aquí.

 function changeImage (value) { var image = document.getElementById('statue'); if (value === 'statue') { image.src = '...'; } else if (value === 'bridge') { image.src = '...'; } }
about 4 years ago · Juan Pablo Isaza Report

0

Bueno, encontré una solución a tu problema.

Básicamente, agregué Oyentes de eventos de clic para cada una de las entradas de radio, luego, cuando se hizo clic en una entrada, obtuve su atributo de valor usando el evento pasado a través de la función de devolución de llamada y lo comparé con cada uno de los elementos de la matriz radioInputs.

Si coincidía, cambié el atributo img src usando el índice de la entrada (que obtuve del bucle forEach) en las direcciones URL de la matriz.

Además, cambié el atributo marcado de la entrada en la que se hizo clic a verdadero y eliminé este atributo de las otras 2 entradas.

Actualización: Realmente no tuve que cambiar los atributos marcados porque todas las entradas tenían el mismo nombre y automáticamente lo hicieron. Lo siento por mi error. Se actualizaron los fragmentos de código en consecuencia.

Aquí está el código (un archivo html y un script):

 let urls = [ 'https://www.history.com/.image/ar_4:3%2Cc_fill%2Ccs_srgb%2Cfl_progressive%2Cq_auto:good%2Cw_1200/MTY1MTc1MTk3ODI0MDAxNjA5/topic-statue-of-liberty-gettyimages-960610006-promo.jpg', 'https://www.history.com/.image/ar_4:3%2Cc_fill%2Ccs_srgb%2Cfl_progressive%2Cq_auto:good%2Cw_1200/MTY1MTc3MjE0MzExMDgxNTQ1/topic-golden-gate-bridge-gettyimages-177770941.jpg', "https://media-cldnry.s-nbcnews.com/image/upload/newscms/2020_26/3392557/200625-mount-rushmore-al-0708.jpg" ] let radioInputs = document.querySelectorAll("input"); radioInputs.forEach(function (input, index) { input.addEventListener('click', handleChange); }); function handleChange(e) { let inputValue = e.target.value; radioInputs.forEach(function (input, index) { if (input.value === inputValue) { let image = document.getElementById("statue"); image.src = urls[index]; } }); }
 <!DOCTYPE html> <html> <body> <!--Statue of Liberty image--> <img id="statue" src= 'https://www.history.com/.image/ar_4:3%2Cc_fill%2Ccs_srgb%2Cfl_progressive%2Cq_auto:good%2Cw_1 200/MTY1MTc1MTk3ODI0MDAxNjA5/topic-statue-of-liberty-gettyimages-960610006-promo.jpg' width="300"> <p>Click the picture to change image.</p> <!-- Radio buttons--> <form> <input type="radio" id="statue-button" name="landmark" checked value="statue">Statue of Liberty<br> <input type="radio" id="bridge-button" name="landmark" value="bridge">Golden Gate Bridge<br> <input type="radio" id="rushmore-button" name="landmark" value="rushmore">Mount Rushmore<br> </form> <script src="script.js"></script> </body> </html>

¡Espero que hayas entendido lo que hice aquí! ¡Buena suerte en tus próximas sesiones de codificación!

about 4 years ago · Juan Pablo Isaza 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!