Mar Cejas Mar Cejas - 1 month ago 8
Ajax Question

jquery element cannot call from displayed json

I'm having a hard time trying to solve this.

Here is my sample code:

$.ajax({
url: 'json.php',
data: {some_data:some_value},
dataType: 'json',
success: function(){
$('.some_element').append('<div class="myElement">Click Me</div>');
}


Then, I have added the following code, this is the code where I am having the problem:

$('.myElement').click(function(){
alert('It works!');//BUT it's not working.
})


Any advice, idea?

Thanks Guys!

Answer

It is not working becuase .click() is a wrapper around .bind() which only binds to elements that exist at the time of the call. Use a .live() event, which will make the event trigger for all current and future elements that match your selector.

$('.myElement').live('click', function() {
    alert('It works!'); //This will work.
})
Comments