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

84
Visualizações
Pass function as argument to another function called inside the first one

I have a function that creates a button with an "onclick" action that calls a second function. This second function will recieve parameters of the first one (includind a function). Just like this:

function funcOne(argFunc, customMsg) {
    let div = document.createElement('div');
    let button = `<button onclick='funcTwo(`+argFunc+`','`+customMsg+`)'>Go!</button>`;
    div.innerHTML = button;
    document.body.appendChild(div);
}

function funcTwo(argFunc, customMsg) {
    argFunc(customMsg);
}

Then, calling funcOne:

funcOne(function(customContent) { alert(customContent) },
'Hello World');

I get "Uncaught SyntaxError: Unexpected end of input" error here:

let button = <button onclick='funcTwo(+argFunc+','+customMsg+)'>Go!</button>;

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

0

In general, avoid onxyz-attribute-style event handlers. Always avoid them when you have a function (rather than string) you need to hook up dynamically. They have several issues, not least that they can only call global functions.

Instead, use modern event handling. There's also no need for HTML parsing:

function funcOne(argFunc, customMsg) {
    const div = document.createElement("div");
    const button = document.createElement("button");
    button.textContent = "Go";
    button.addEventListener("click", () => {
        funcTwo(argFunc, customMsg);
    });
    div.appendChild(button);
    document.body.appendChild(div);
}

function funcTwo(argFunc, customMsg) {
    argFunc(customMsg);
}
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