Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
Cómo agregar un método de clase como un evento a un botón html

Tengo una clase js llamada Encabezado, que, cuando se llama al método render (), agrega el código de encabezado html a todas las páginas del sitio.

Esta clase, además del método render(), también tiene un método hello():

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

La pregunta es, ¿cómo agrego este método como un evento al botón de encabezado?

He intentado hacerlo así:

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

Pero muestra un error en la consola: Uncaught SyntaxError: Token inesperado '{'

¿Cómo agregar un método de clase como evento a un botón html?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Primero, crea un objeto de tu clase. Luego use el objeto para llamar al método.

Ejemplo:

 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 Report

0

¿Quiso decir algo como esto?

Puede usar HTMLelement.addEventListener para escuchar eventos específicos, como click en un evento en un botón, y luego proporcionar una función de devolución de llamada para realizar cuando se activa ese evento.

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!