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
you need to use the live function to make sure that the click event gets binded to elements that have been added to the DOM after the page has been loaded:
$('#something a').live('click',function() .....
精彩评论