I have generated some html links with jQuery and appended it to some div
but it seams that i can't call click method now, when these elements are appended (it worked ok when they were hardcoded into html)
$('#something a').click(function() ...
Does anyone know a solution for this?
Use .delegate()
for these cases:
$('#something').delegate('a', 'click', function() {
This attaches a click
handler on #something
, rather than direction to the <a>
elements within...so it works on anchors appended later. The alternative (worse for a few reasons) version is .live()
like this:
$('#something a').live('click', function() {
What also works is to add the [click] event when appending the elements, like so:
$('<someElement>').click(function(){
$('<someElement>').append('<htmlCodeToAppend>');
$('<appendedElement>').click(function() { /* do something */ });
});
This approach does the job, but I'm not sure if there are any caveats to it -- maybe one of the pros could kindly step in here.
Cheers, Erik
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With