I am trying to make simple list with ability to add and delete elements. For now I am working on adding and performing a simple action on each of list elements object (existing and added). Unfortunately I have met some difficulties with that. I am able to modify objects that are created at the beginning, but not one added during “webpage working”.
First of all my idea was to add AJAX to this, but I don’t think it is the easiest way.
I think that some time ago (I don’t remember where) I read how to make this work, but now I don’t know. I would be really glad if someone would help me with this or at least give a link to good explanation of this.
There is what I have done so far (well this is mostly just a scratch, but the main idea is in it): http://jsfiddle.net/sebap123/pAZ7H/0
$("li").click(function() {
$(this).text("new text");
});
$("#addButton").click(function() {
$(".list").append(
$('<li>').append($('<span>').append("added li")));
});
Thank you for all responses.
You just need to use event-delegation, with the
on()method:JS Fiddle demo.
The problem you were experiencing is that jQuery can only directly bind events to already-present elements (present at the point of event-binding); the
on()approach binds the action to the element to which the new content is added (or an ancestor element of the newly-added elements), identifies the events to listen for'click'(a space-separated list of events), that match the selector (li) and then the function performs the required actions.If you’re using jQuery 1.7 (or later)
on()should be used, for versions of jQuery < 1.7,delegate()should be used instead (which does more or less the same thing, but reverses the event-list and the selector parameters):JS Fiddle demo.
References:
delegate().on().