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

122
Visualizações
How to add a class method as an event to a html button

I have a js class called Header, which, when the render () method is called, adds the html header code to all pages of the site.

This class, in addition to the render () method, also has a hello () method:

hello() {
    console.log('Hello');
}

The question is, how do I add this method as an event to the header button?

I've tried doing it like this:

<button onclick="${this.hello}">Call/button>

But it displays an error in the console: Uncaught SyntaxError: Unexpected token '{'

How to add a class method as an event to a html button?

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

0

First, create an object of your class. Then use the object to call the method.

Example:

class Header {
   render(){
      // render other things
      // also render: <button onclick="header.hello();">Call</button>
   }
   hello() {
     console.log('Hello');
   }

   // other methods here...
}

var header = new Header();
header.render();
about 4 years ago · Juan Pablo Isaza Relatório

0

Did you mean something like this?

You can use HTMLelement.addEventListener to listen for specific events like click event on a button, and then provide a callback function to perform when that event is triggered.

const btn = document.getElementById('test');

class Header {

    render(element) {
        element.addEventListener('click', () => this.hello());
    }
    hello() {
        console.log('Hello');
    }

}

const header = new Header();
header.render(btn);
<button id="test">Click me</button>

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