问题
I've use jQuery templates (http://api.jquery.com/jquery.tmpl/) to render lists on pages based on remote content, this is all working well, however when I apply a class to the content and have a click event for the class dynamic template content doesn't respect the action where as hard coded content works fine.
I've slightly edited the basic demo which ships with the tmpl plugin to add a static list as a proof of concept: http://jsfiddle.net/3eVrR/2/
Clicking the static 'bar' link generates an alert as I'd expect. Clicking any of the buttons (Cartoons or Drama) to generate a list then clicking they hyperlink (it has the same class as the hard coded link) does not fire the alert.
Can anyone see what the problem is? Firebug does not show any errors, on inspection the classes for both the static and dynamic content is the same.
Thanks
回答1:
As aleksv pointed out, traditional .click()
handlers only apply to elements which can be selected when the handler is initialized. In this case, a .live()
(or .delegate()
) handler would be a better approach:
// This handler will apply to any .getPage element, even if it is created
// after this handler declaration has been executed.
$('.getPage').live('click', function(){
alert('clicked element with getPage class');
});
回答2:
I played around with your code and now it works: http://jsfiddle.net/3eVrR/5/ . You have to initialize events when all the content is loaded. You initialized the events when there were no movie entries. Then you added the movie entries and JS didn't know they were there.
来源:https://stackoverflow.com/questions/5962556/jquery-tmpl-plugin-problems-with-template-results-from-dynamic-content-bug