0

Page1.php

<span class='Clic_function' aria-hidden='true' id='1'></span>
<span class='Clic_function' aria-hidden='true' id='2'></span>
<span class='Clic_function' aria-hidden='true' id='3'></span>

(I have the same function button for alots but diferent ID)

when they its load from page with ajax dont works

Page2.php

<html>
<input type="button" id="reload">
<div id="box">
<span class='Clic_function' aria-hidden='true' id='1'></span>
<span class='Clic_function' aria-hidden='true' id='2'></span>
<span class='Clic_function' aria-hidden='true' id='3'></span>
</div>
<script>
    $(".Clic_function").click(function () {
        alert("Hi");
    });

  $("#reload").click(function () {
        $.ajax({
            url: "Page1.php",
            context: document.body,
        }).then(function (result) {
            $("#reload").html(result);
         }
   });
</script>
</html>

Only work at first time but when push reload the script (alert) dont work again, i can see the page its loaded fine but script no.

2 Answers2

1

You need to use event delegation and attach the event to a higher level of the DOM. I attached it to the document in the example.

$(document).on('click', '.Click_function', function(){
    alert("Hi");
});
Hugo Sousa
  • 1,904
  • 2
  • 15
  • 28
1

You need to delegate the click event to something that exists when the page runs the first time -

$(document).on('click', ".Clic_function", function () {
     alert("Hi");
});

jQuery is only aware of the elements in the page at the time that it runs, so new elements added to the DOM are unrecognized by jQuery. To combat that use event delegation, bubbling events from newly added items up to a point in the DOM that was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go that high up the DOM tree. Ideally you should delegate to the nearest parent that exists at the time of page load.

Community
  • 1
  • 1
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119