After reloading, the jQuery system does not work

Asked

Viewed 57 times

1

When I click a button .click, my JS runs a function and updates the fields with the class .click. But why when HTML is updated and clicked on .click again nothing happens as if the class does not exist?

Javascript:

$(function () {
    $(".click").click(function () {
        $.get("http://localhost/test/api.php", function (data) {
            alert(data);
            $(".content").html(data);
        })
    })
})

HTML:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

<div class="content">
    <div class="click">ops</div>
</div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script src="functions.js"></script>
</body>
</html>

When I first click on .click, search for the HTML of api.php (<div class="click">eita</div>), which is placed in .content.

But if I click again on .click after reloading, content with AJAX’s HTML simply does nothing else. Why?

  • What is the HTML of the page http://localhost/test/api.php? Edit the question to include it.

  • code <div class="click">Eita</div>

1 answer

2

The problem is that you are attaching the Listener of event in the <div class="click">ops</div>, that will be removed from the page when you use the method html. Thus, your Listener event will also be lost.

You must make use of the mechanism of event delegation to resolve this. Attach the Listener in .content, that is not removed from the page:

See an example (no AJAX, but illustrates well):

$('.content').on('click', '.click', function() {
  console.log($(this).text());
  
  $('.content').html('<div class="click">Segundo</div>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="content">
  <div class="click">Primeiro</div>
</div>

Note, that the Listener was attached in .content, but will be delegated to the selector elements .click (second argument of the method on).

  • SHOW ! THE PROBLEM WAS THAT SAME MY FRIEND, VLLW

  • 1

    @Gilbertogonçalves, If this answer solved your problem and there was no doubt left, mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. If you still have any questions or would like further clarification, feel free to comment.

  • 1

    @Gilbertogonçalves see how to thank.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.