jQuery: bind generated elements
thank you for taking time to look at this.
I am trying to code my very first jQuery plugin and have run into my first problem. The plugin is called like this
<div id="kneel"></div>
<script type="text/javascript">
$("#kneel").zod(1, { });
</script>
It takes the first option (integer), and returns html content that is dynamically generated by php. The content that is generated needs to be bound by a variety of functions (such as disabling form buttons and click events that return ajax data.
The plugin looks like this (I have included the whole plugin in case that matters)...
(function( $ ){
$.fn.zod = function(id, options ) {
var settings = {
'next_button_text': 'Next',
'submit_button_text': 'Submit'
};
return this.each(function() {
if ( options ) {
$.extend( settings, options );
}
// variables
var obj = $(this);
/* these functions contain html elements that are
generated by the get() function below */
// disable some buttons
$('div.bario').children('.button').attr('disabled', true);
// once an option is selected, enable the button
$('input[type="radio"]').live('click', function(e) {
$('div.bario').children('.button').attr('disabled', false);
})
// when a button is clicked, return some data
$('.button').bind('click', function(e) { e.preventDefau开发者_如何学Pythonlt();
$.getJSON('/returnSomeData.php, function(data) {
$('.text').html('<p>Hello: ' + data + '</p>');
});
// generate content, this is the content that needs binding...
$.get('http://example.com/script.php?id='+id, function(data) {
$(obj).html(data);
});
});
};
})( jQuery );
The problem I am having is that the functions created to run on generated content are not binding to the generated content. How do I bind the content created by the get()
function?
You may find the .delegate
or .live
to be useful. They are able to bind events to current and future elements in the document, instead of only documents found at the time of the call.
EDIT
Here is a working example of what I mean: http://www.jsfiddle.net/bradchristie/39Gt5/ Note that I don't make any further calls to the delegate function, but it is adding new paragraphs and buttons as you click the button, and the click event is automatically bound.
UPDATE
For those of you finding this post and using jquery 1.8+, .delegate
/.live
have been deprecated and replaced by .on
. The linked reference shows exmaple of how to convert your code to use the new .on()
method as well.
精彩评论