I've got two dynamic generated (from PHP file) divs. This divs are like this:
Where X and Y are numbers generated dynamically from a php file. How can I get this id (number) when, for expample, I click on this divs?
I've tried in this way:
$('.myclass').click(function(){
alert(this.attr("id"));
});
But in this way I get only the first id (the first element of myclasses).
How can I fix it?
解决方案
try this instead:
$('.myclass').live('click', function() {
alert(this.id); //or alert($(this).attr('id'))); for the jQuery method
});
Binding events using the $.live() function will bind events to elements that do not yet exists, so when you add new div.myclass elements dynamically they will be bound as well.
Please Note: .live() is now deprecated, use .delegate() or .on() instead.
$(document).on('click', '.myclass', function() {
alert(this.id);
});