Soy muy nuevo en la programación. He usado w3schools y freecodecamp para aprender. Conozco los conceptos básicos de objetos, matrices, funciones y bucles. Sé que puedo escribir algo como esto para cambiar una imagen.
function a(b) {var t; if(b === 1){t = "image.jpg"} document.getElementById("aide").src= t; } <br>button onclick="a(1)" <br> img id="aide src="some.image"¿Cómo haría esto un programador profesional? ¿Eso se llama dom ya que necesito escribir onclick en html?
y... Puedo hacer objetos/matrices como var x = [{ rock: "Metallica" }];. Quiero una barra type="text" en una página web que muestre Metallica cuando un usuario escriba Rock en el campo de texto y lo envíe. ¿Cómo, y sin dom si es posible?
Si desea cambiar una imagen, puede cambiar su fuente:
// setting the variables used later var btnNewImage = document.getElementById('btn-new-image') var imageContainer = document.getElementById('image') var counter = 1 // creating the string that will // be the src of the image function getImgSrc(currentCounter) { // the current counter makes it possible to // load different images on click return "https://picsum.photos/200/300?random=" + currentCounter } // setting the src attribute of the imageContainer // modifying the counter function setImage() { imageContainer.src = getImgSrc(counter) // counter is mutated, so if it's called again // it will be the next number counter++ } // adding event listener to the button // instead of onclick handler btnNewImage.addEventListener('click', function() { // calling the setImage function, that will set // the src attribute of the image setImage() }) // calling the setImage function for the first time // so an image shows up on page load setImage() <button id="btn-new-image">NEW RANDOM IMAGE</button><br /> <img id="image" src="" />El fragmento anterior usa algunas cosas que no se recomiendan:
var en lugar de let & constcounter mutante, llamada a la función setImage() , referencia a imageContainer dentro de la función setImage() , etc.)Deben evitarse, pero creo que en este punto no hace ninguna diferencia.
La API que usé para las imágenes: Lorem Picsum
El truco es que addEventListener no hace nada, hasta que se hace clic en el botón en el que se ha registrado. Cuando ocurre el clic, ejecuta la función que se le agregó.