This is the workflow:
- Add elements dynamically to a div container
- Register click event for this elements (using jquery custom function)
- Trigger the element event
According to the flow above, I can’t get the new element event works, because it never is triggered. This is my scenario:
The idea is that when you click over “element” its ID attribute should be printed in .log div
Edit:
I have tested all answers and all of them work fine 🙂
In jsFiddle, the code is automatically put in a
$(document).readyblock. So, what’s happening is your$(document).readyis ran immediately. This means it’s ran beforejQuery.fn.showIDis set.Also,
$(".element").showID();binds the event to.elements that exist at that time. New elements won’t have the event bound. You need to either use event delegation (which makes theshowIDplugin useless), or callshowIDafter adding the element (making sure not to re-bind to old elements).P.S. Inside a jQuery plugin
thisis already a jQuery object, no need to use$(this).