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

113
Visualizações
JS stop working after jquery .load content

Please help me to understand why js stop working after .load THE SAME CONTENT in div.

<main class="container">
    <div id="reload_div">
        <div id="color_div" style="width:100px;height:100px; background:red; margin-bottom: 100px">
            orig
        </div>
        <button id="make_it_green" type="submit" class="btn btn-sm btn-primary">
            make it green
        </button>
    </div>
    <button id="reload_btn" type="submit" class="btn btn-sm btn-primary" style="margin-top:20px">
        reload
    </button>
</main>

<script>
$("#make_it_green").click(function(){
  $("#color_div").css("background","green")
}); 

$("#reload_btn").click(function(){
  $("#reload_div").fadeTo(300,0, function () {
    $("#reload_div").load ("reload.php", 
    {  }, function () {
        $("#reload_div").fadeTo(300,1, function () {
        });
    });
  });
}); 
</script>

After .load the same content in "reload_div" #make_it_green button stop working! Why?

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

0

When you run your code as you have posted it, the event handler is added to the make_it_green button.

Once you load the new content with jQuery the element to which the handler was attached no longer exists, so the event handler no longer exists. You load a new element with the same name, but there's no event handler attached unless you attach the event handler again.

Alternatively, attach the event handler to the containing div and delegate the event handling.

$("#reload_div").click(function(e){
        e.preventDefault();

        // Check the id of the original target element. If it's 
        // our button, change the colour.
        if (e.target.id === "make_it_green") {
            $("#color_div").css("background", "green");
        }
    });

See this page on MDN for a detailed discussion of event delegation

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