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

148
Visualizações
Sending a function with a parameter through an .onclick listener

I'm a beginner web developer who is in the process of putting together a simple website that will use an API to display data from various cities based on different buttons a user can click. I've written a general function that takes in a city parameter, runs it through the API, and sends the appropriate data back to my HTML page. I'm just having trouble getting the event listener for my buttons to work as expected.

Listener examples:

city1button.onclick = cityInfo("city1");
city2button.onclick = cityInfo("city2");

Based on some research, I now realize that my code is invoking my functions before a button is pressed. I've found some more elaborate solutions online but was wondering if there is a simple way that could ideally be kept in one line. Thanks in advance. I really appreciate the help.

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

0

Try wrapping your named function in an anonymous one, like this:

var outer = function(){
      function innerFunction(){
      }
    }

This puts it inside the scope of another function rather than your whole window/program on initial load.

about 4 years ago · Juan Pablo Isaza Relatório

0

Try this code

document.getElementById("aaa").addEventListener("click",function(){
        var x = "xx";
        functionName(x);
    });

about 4 years ago · Juan Pablo Isaza Relatório

0

There is a clean way to attach an event handler function to a specific target element:

  1. Grab the element from the DOM and store it into a variable;
  2. Attach event handler to the element with the function addEventListener(eventType, callback) like follows;

example

// grab the targets
const button_1 = document.getElementById('clickable_1');
const button_2 = document.getElementById('clickable_2');

// add events to the targets
button_1.addEventListener('click', () => { console.log('clickable 1 function ...'); });
button_2.addEventListener('click', () => { console.log('clickable 2 function ...'); });
<button id="clickable_1">clickme 1</button>
<button id="clickable_2">clickme 2</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