JQuery .get and generated PHP. How to bind events?
Although I have research this topic I don't really seem to understand how to make it work.
Situation:
The following code is used to show the new_comments Div on my page.
<script type="text/javascri开发者_开发知识库pt">
$(function(){
$('#lnk_comment').click(function() {
//alert('Handler for .click() called.');
$("#comment_new").show();
$('#new_comment').focus();
});
});
</script>
This code works great when these div tags are generated by PHP.
The Problem:
If I instead query this PHP page through JQuery using the .get Method outputting the result using JQuery instead, it seems that the function above no longer works. It seems as though the click() event doesn't seem to bind to the lnk_comment tag.
My Guess is that the DOM is loading first and the JQuery data is loading after.
The Question:
How do you add/bind a Click event to tags that have been generated through JQuery/JavaScript during run time?
Other Thoughts:
I have found something in regards to a .delegate function in JQuery but after numerous attempts, I don't really seem to get it.
Thank you for any examples.
Use live()
instead:
<script type="text/javascript">
$(function(){
$('#lnk_comment').live('click', function() {
//alert('Handler for .click() called.');
$("#comment_new").show();
$('#new_comment').focus();
});
});
});
</script>
This will automatically bind the events to newly added DOM members that match the selector (in this case #lnk_comment
).
精彩评论