Tengo algunos problemas con mi javascript
tengo dos imagenes Cuando quiero hacer clic aleatoriamente en una imagen, se reemplazará con la imagen en el JS. si hago clic en la imagen restante, también se reemplazará como la imagen anterior, pero la imagen anterior volverá a la imagen original. ¿¿Cómo puedo hacer eso??
Muchas gracias.
Este es mi código. Perdón por mis malas habilidades en inglés.
function openPresent(event){ event.target.src ='https://i2.wp.com/gsviec.com/wp-content/uploads/2020/02/coder-dev-1.jpeg?fit=900%2C500&ssl=1'; } const image = document.querySelectorAll('img'); let i; for(i=0;i<image.length;i++){ image[i].addEventListener('click',openPresent); } <!DOCTYPE html> <html> <link rel="stylesheet" type="text/css" href="style.css"> <head> <style> </style> <script src='script.js'defer></script> </head> <body> <h1>Click for a present:</h1> <img src=https://timviec365.com/pictures/images/coder-la-gi-3.jpg> <h1>Hello World</h1> <img src="https://img.timviec.com.vn/2020/10/coder-la-gi-2.jpg"> </body>Puede guardar su imagen original src en una matriz. Al cambiar el src al hacer clic, revierta todos los src s al original y simplemente cambie el de destino.
Echa un vistazo a esto:
function openPresent(event){ const image = document.querySelectorAll('img'); for(let i=0;i<image.length;i++){ image[i].src= originalImagesSrcArray[i]; } event.target.src ='https://i2.wp.com/gsviec.com/wp-content/uploads/2020/02/coder-dev-1.jpeg?fit=900%2C500&ssl=1'; } const image = document.querySelectorAll('img'); let i; let originalImagesSrcArray = []; for(i=0;i<image.length;i++){ originalImagesSrcArray.push(image[i].getAttribute('src')); image[i].addEventListener('click',openPresent); } console.log(originalImagesSrcArray); <!DOCTYPE html> <html> <link rel="stylesheet" type="text/css" href="style.css"> <head> <style> </style> <script src='script.js'defer></script> </head> <body> <h1>Click for a present:</h1> <img src="https://timviec365.com/pictures/images/coder-la-gi-3.jpg"> <h1>Hello World</h1> <img src="https://img.timviec.com.vn/2020/10/coder-la-gi-2.jpg"> </body>