-1

i need your help for this question :

I do this with ajax on my index.php file :

$.ajax({
                type: "POST",
                url: "ajax/newTask.php",
                success: function(reponse){

                    $("#containerSidebarRight").prepend(reponse);

                }
            });

This is my newTask.php file :

<div class="test">
Hello, i'm a test              
</div>

And it works well. What i need to do is to bind this function to the test class.

$(".test").click(function(){
      alert("test");
    });

If i set this function in my index.php, it doesn't work because the function isn't binded to the content loaded with ajax.

If i set this function in the newTask.php, i got the function in my code everytime i go the ajax call and it's not really optimized.

What is the best solution to do what i want to do ?

Thanks :)

Alan
  • 47
  • 3
  • 12

2 Answers2

1

It looks like you want to set an event handler on an element that doesn't yet exist. In this case, use delegation:

$(document).on("click", ".test", function(){
  alert("test");
});
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1
$(document).on("click",".test", function () {
}

should do the trick.

Carka
  • 161
  • 5