From looking at other posts I\'ve tried to add live() and on() to my code but the click function only works once and then wont work anymore. Can someone point out what I\'m
I am assuming (by your code) that the .delete_it
item is inside the #step_list
element.
So when you replace its html with the ajax results you remove the bound handlers as well..
You need to bind the handler to an element up in the DOM hierarchy that does not get removed, for example the #step_list
itself..
So change the binding from
$(".delete_it").on('click',function() {
to
$("#step_list").on('click','.delete_it', function() {
Events are bound to DOM nodes. If the DOM which you are binding to is removed the associated event will likely be removed too. You can fix this or you can make use of the "bubbling up" nature of DOM events. For example, say my HTML was this:
<div id="container">
<div class="item delete_me_on_click"></div>
<div class="item delete_me_on_click"></div>
<div class="item delete_me_on_click"></div>
</div>
What I could do is bind to the #container
or to document
to listen to any click event and inspect the event's target to see if I want to take action. An example of that for the above HTML:
$('#container').on('click', function (event) {
var target = $(event.target);
if (target.hasClass('delete_me')) {
target.remove();
}
});
Which is the same as:
$('#container').on('click', '.delete_me', function (event) {
$(event.target).remove();
});
Or I can even listen on the document level:
$(document).on('click', '.delete_me', function (event) {
$(event.target).remove();
});
Here is a working example: http://jsfiddle.net/Kcapv/
Note that event.stopPropagation()
if used on a child node will stop the event bubbling up so if you try this approach you need to be careful to watch for use of stopPropagation.
It's hard to see from here. Would you mind sharing the HTML? Without knowing what the data.success contains doesn't make it easy also. Does the .html(data.success) affect the delete buttons in any way?
And are you sure you did the .live() right?
$('.delete_it').live("click",function(){
});
I might be able to help if you could provide more info.