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

242
Views
¿Cómo cambiar la imagen en JavaScript al hacer clic en el botón cuando se usa un servidor JSON simulado?

Tengo un archivo 'db.json' y este archivo tiene datos relacionados con las imágenes de los diferentes personajes de Star Wars que se extrajeron de la API de Star Wars.

Usé esto en mi 'script.js':

 function getPeople() { let numberPeople = Math.floor((Math.random()*83)+1) let apiUrl = 'https://swapi.dev/api/people/' + numberPeople fetch(apiUrl) .then(function(response){ return response.json() }) .then (function(json){ console.log(json) let name = document.getElementById('name') let DOB = document.getElementById('DOB') let height = document.getElementById('height') let weight = document.getElementById('weight') let gender = document.getElementById('gender') name.innerText = `Name: ${json['name']}`; DOB.innerText = `Date of Brith: ${json['birth_year']}`; height.innerText = `Height: ${json['height']} cm`; weight.innerText = `Weight: ${json['mass']} kg`; gender.innerText = `Gender: ${json['gender']}`; fetch(`${json['homeworld']}`) .then(function(response) { return response.json() }) .then(function(json) { console.log(json) let homeWorld = document.getElementById('home-world') homeWorld.innerText = `Home Planet: ${json['name']}`; }) fetch('./db.json') .then(results => results.json()) .then(data => { console.log(data.people) var url = data.people[numberPeople-1]['imgUrl'] var image = new Image(); image.src = url document.getElementById('header').appendChild(image) })

El código en cuestión comienza con "fetch('/db.json)", por lo que la variable 'numberPeople' solo pertenece a la identificación del personaje. Por ejemplo, Luke Skywalker, su url es https://swapi.dev/api/people/1 , mi página web ha aleatorizado el aspecto del número para que en cada clic se haga un nuevo número con un carácter diferente.

El servidor JSON simulado (db.json) que se creó tiene URL para imágenes y, a través de la manipulación de DOM, dependiendo de la variable 'numberPeople', se agregará la imagen según el carácter.

Mi problema es que cuando hago clic en el botón:

 peopleButton.addEventListener('click', getPeople)

Las imágenes se corresponden correctamente con el personaje, sin embargo, cuando vuelvo a hacer clic en él, aparece la nueva imagen, así como la imagen anterior. Probé diferentes soluciones, pero no estoy seguro de cómo hacerlo cuando se trata de un servidor JSON.

¿Hay alguna manera de que pueda hacerlo? Soy nuevo en el uso de servidores JSON y cualquier ayuda sería genial.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Por favor, lea aquí sobre replaceChild:

https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild

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!