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

229
Visualizações
How to use onClick function inside innerHTML

This is my JS file, it is one of reusable HTML components since I'm not using any framework. Before this I'm using ReactJS, since for some reason, I required not to use any framework for frontend.

My question is I want to make onClick function for the button. I thought it is the same thing as using JSX in ReactJS but it doesn't work. I want to add the <script> tag in the innerHTML but I don't think it is relevant because this is already a javascript file.

class Header extends HTMLElement {
    connectedCallback() {
        this.innerHTML =
           `
             <button onclick="">Try it</button>
           `
    }
}

customElements.define('main-header', Header);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

<button onclick="fn()">Try it</button>
Or you can write code in the quotes directly:
onclick="console.log('click')"

about 4 years ago · Juan Pablo Isaza Relatório

0

HolaPz is correct, but to more clearly demonstrate-

function buttonClicked()
{
  console.log("You son of a gun, you did it");
}

class Header extends HTMLElement {
    connectedCallback() {
        this.innerHTML =
           `
             <button onclick="buttonClicked()">Try it</button>
           `
    }
}

customElements.define('main-header', Header);

NOTE: when buttonClicked is called, the "this" context will be set to the Window object and only top-level functions will be available. Depending on how you want to code going forward, it might make sense to use this.querySelector inside connected callback to get a reference to the button and then manually add a bound function or event listener (via addEventListener) to it.

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