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

112
Visualizações
Pass an array of objects to another function onclick

I just want to ask how to pass an array of objects to another function. I have a function

 function btnB(weekly) {
    console.log(weekly);
 }

 function btnA() { 
    const array = [{ abc : 123 }, { def : 456 }]        
    div.innerHTML = `<div onclick="btnB(${array[0]});"`;
    divList.appendChild(div);        
 }

 btnA();

And I'm getting an error

Uncaught SyntaxError: Unexpected identifier
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can't substitute an object like that in a template literal. It converts the object to a string, which returns [Object object].

Use JSON.stringify() to convert it to an object literal.

function btnA() { 
    const array = [{ abc : 123 }, { def : 456 }]        
    div.innerHTML = `<div onclick='btnB(${JSON.stringify(array[0])});'`;
    divList.appendChild(div);        
 }

You also should use single quotes around the onclick value, because JSON uses double quotes around the object keys.

about 4 years ago · Juan Pablo Isaza Relatório

0

function btnB(weekly) {
   console.log(weekly);
}

function btnA() { 
   const array = [{ abc : 123 }, { def : 456 }];
   const div = document.createElement('div'); // delete if useless
   div.addEventListener('click', () => {
     btnB(array[0])
   });
   divList.appendChild(div);        
}
about 4 years ago · Juan Pablo Isaza Relatório

0

I'm assuming the [0] is part of your attempt to solve this, but based on the question asking to pass an array of objects to the click handler, I'll refer to that instead.

Inline event handlers are deprecated and problematic anyway, but using them in HTML generated by JavaScript completes the circle in an absurd way. It would be a lot easier and more robust (and secure) to attach the click handler via JavaScript as well, as follows:

const array = [{ abc: 123 }, { def: 456 }]        
div.innerHTML = '<div></div>' // Just the inner div without onclick
div.firstElementChild.addEventListener('click', () => btnB(array))
divList.appendChild(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