Unexpected JQuery behaviour when accessing dynamically generated elements by class
I have the following JQuery code that dynamically generates some checkboxes:
var container = $('#checkbox_list_container');
var html = '<input type="checkbox" class="selection_checkboxes" name="ids[]" value="1" />';
conta开发者_C百科iner.append($(html));
I also have the following code that pops up an alert when any of these checkboxes are clicked:
$(document).ready(function() {
$('.selection_checkboxes').click(function() {
alert('click detected');
if ($(this).attr('checked'))
{
if ($('.selection_checkboxes:checked').size() > 3)
{
alert('You can only select up to 3 items');
return false;
}
}
});
});
For some reason, JQuery is unable to detect when any of the dynamically generated checkboxes have been clicked on and display the alert('click detected') message, let alone get a count of all the checked checkboxes with the same class name.
Any idea what I'm doing wrong?
You need to use jQuery's live
to attach handlers to dynamically created elements:
$('.selection_checkboxes').live('click', function() {
//stuff
});
If all your checkboxes are in #checkbox_list_container
, then delegate
is more efficient:
$('#checkbox_list_container').delegate('.selection_checkboxes', 'click', function() {
//stuff
});
- http://api.jquery.com/live/
- http://api.jquery.com/delegate/
精彩评论