读取AJAX返回的数据

I'm doing an ajax request which populates on my html page. I have an anchor tag on the ajax response page. I wanted to access the html anchor tag through its id and display an alery.

My code is:

<div id="response">
</div>

$.post("destination.php",function(data){
$("#response").html(data);
});

The page after the ajax query would be:

<div id="response">
<a href="some_link.php" id="link_test">Click Me</a>
</div>

And now I want to access this data using jQuery:

$("#link_test").on('click',function(){
alert("You Clicked Me");
});

But I'm not able to do this on my page since it is an ajax request and the ids are not refreshed after the ajax request. So the browser doesn't recognize the id and this does code does is useless.

Please help me out.

This should work for you:

$('#response').on('click', "#link_test", function(){
    alert("You Clicked Me");
});

Event delegation:

$("#reponse").on("click", "#link_test", function(){

You can use event delegation This mean you have to attach the event listener to the first common ancestor of those buttons.

This is a good choice when many elements have to trigger the same routine an even more if some of them may be added to the DOM in the futur via AJAX (This keep the page from having to many event handlers attached to it)

Delegation syntax

// Event delegation
$( "#firstCommonAncestorThatStillInThePage").on("click", 'a', function() {
    if($(this).is('#link_test')){
        alert( $( this ).text() );
    }
});