Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

284
Visualizações
Cannot pass Object as param to onClick while iterating with innerHTML

I am currently iterating through a list of movies and want to be able to make each element clickable and pass their respective movie information to the click event.

Here is how I iterate through my data. I want to be able to pass the movie information to the click event so that when I click on a movie, I can display its information :

const APIKEY = 'api_key=blabla....';
const BASE_URL = 'https://api.themoviedb.org/3';
const API_URL = BASE_URL + '/discover/movie?sort_by=popularity.desc&' + APIKEY;
const IMG_URL = 'https://image.tmdb.org/t/p/w500';
const SEARCH_URL = BASE_URL + '/search/movie?' + APIKEY;

const main = document.getElementById('main')
const form = document.getElementById('form')
const search = document.getElementById('search')

    getMovies(API_URL);

function getMovies(url) {
    fetch(url).then(res => res.json()).then(data => {
        showMovies(data.results);
        console.log(data.results)
    })
}

function showMovies(data){
    main.innerText = '';
    data.forEach((movie, index) => {
        let {title, poster_path, release_date, overview} = movie;
        let movieEl = document.createElement('div');
        movieEl.classList.add('movie');
        movieEl.innerHTML = `
            <div onclick="showMovieInfo(${movie[index]})" style="cursor: pointer;">
                <img src="${IMG_URL + poster_path}" alt="${title}">
                <div class="movie-info">
                    <h3>${title}</h3>
                    <span>${release_date.slice(0,4)}</span>
                </div>
    
                <div class="overview">
                    ${overview}
                </div>
            </div>
        `
        main.appendChild(movieEl)
    })
}

For Now i just want to be able to console.log the movie info for each

function showMovieInfo(movie) {
      console.log(movie)
}

Currently I get this error when I click on an element: Uncaught SyntaxError: Unexpected identifier

Do you guys know what I could do to make it work?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The problem here ist that the "movie" object don´t exist in the "innerHTML" context. One Solution would be to serialise the movie Object or pass the Index and than get the Object from the data Array.

You can´t pass an Object to innerHTML so you have to pass a Primitive values like string or number.

    const main = document.getElementById('main');
    const IMG_URL = "/"
    const data = [{title: "New Movie", poster_path:"",release_date:"2021-10-31", overview:"nice movie" }];

    function showMovieInfo(movieId){
      console.log(data[movieId])
    }

    function showMovies(data){
          main.innerText = '';
          data.forEach((movie, index) => {
              let {title, poster_path, release_date, overview} = movie;
              let movieEl = document.createElement('div');
              movieEl.classList.add('movie');
              movieEl.innerHTML = `
                  <div onclick="showMovieInfo(${index})" style="cursor: pointer;">
                      <img src="${IMG_URL + poster_path}" alt="${title}">
                      <div class="movie-info">
                          <h3>${title}</h3>
                          <span>${release_date.slice(0,4)}</span>
                      </div>

                      <div class="overview">
                          ${overview}
                      </div>
                  </div>
              `
              main.appendChild(movieEl)
          })
      }
      
     showMovies(data);
    <div id="main">

    </div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda