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

109
Visualizações
Use one() in inline onclick attribute

I have a function that is triggered on an inline onclick.

What I want is for that function to get called only once but don't know how to do that with an inline onclick. It's working at the moment but runs everytime the user clicks rather than just once.

This is how I have it:

HTML

<div class= "container" onclick="modal('#modal')"></div>

I have tried having it as a Jquery function as follows and remove the above click but that is not working either:

$(".container").on( "click", modal( '#modal') {
  alert( "The event happened!" );
});

Any idea how to make it so the function only runs once?

Thank you

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

0

If you wish to use jQuery's one(), you'll need to remove the onclick from the HTML, and change the JS to read:

$( ".container" ).one( "click", function() {
  alert( "The event happened!" );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class= "container">Container</div>

This way, the alert() will only show on the first click.


If you wish to use the on() as stated in your question, use $(this).off('click'); to remove the event listener after the fist press:

$( ".container" ).on( "click", function() {
  alert( "The event happened!" );
  $(this).off('click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class= "container">Container</div>

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