I\'m trying to reorganize my code and make it more unobstrusive.
Mainly, there is a link for performing an action. If you click on the link, the action is performed via
Since you are dynamically adding new items to the DOM, you will have to register the click
handler again on the new items. jQuery sets the handler when you call $('...').click(...)
.
Just demonstrating the use of .end() for a more fluid solution:
$(function() {
$(".add2").click(function(){
return $(this).parents(".place")
.find(".add2")
.hide()
.end()
.find(".actions")
.append("<span class=\"added\">Added!</span> <a class=\"undoadd2\" href=\"#\">Undo</a>");
});
$('.undoadd2').live('click', function(){
return $(this).parents(".place")
.find(".actions")
.find("span.added, a.undoadd2")
.remove()
.end()
.end()
.find(".add2")
.show();
});
});
The click handler isn't being picked up when you append the element to the DOM. Try using jQuery to register the click handler by changing the line(s) that look like:
$("#" + placeId + " .actions").append("<span class=\"added\">Added!</span> <a class=\"undoadd\" href=\"#\" onclick=\"undoAddPlace('" + placeId + "'); return false;\">Undo</a>")
To
$("#" + placeId + " .actions").append("<span class=\"added\">Added!</span> <a class=\"undoadd\" href=\"#\" >Undo</a>");
$('#' + placeId + " .actions").find("span:last").find("a").click( function() {
undoAddPlace( placeId );
return false;
});
You might be able to do it more simply, but it looks like you could be adding more than one span to the paragraph so I went conservative. You could also probably chain off append, but I thought the reselect made the point clearer.
Wow!! Thanks to all of you!
I've read about the live event and final working code is:
$(function() {
$(".add2").click(function(){
var placeId = $(this).parents(".place").attr("id");
$("#" + placeId + " .add2").hide();
$("#" + placeId + " .actions").append("<span class=\"added\">Added!</span> <a class=\"undoadd2\" href=\"#\">Undo</a>");
return false;
})
$('.undoadd2').live('click', function(){
var placeId = $(this).parents(".place").attr("id");
$("#" + placeId + " .actions").find("span.added, a.undoadd2").remove();
$("#" + placeId + " .add2").show();
return false;
});
Previously I used remove() for delete the text that offers to perform the action. I've changed it for hide/show so I don't have to use live also in the first function.
Thanks again!
Since you are dynamically adding new items to the DOM, you will have to register the click handler again on the new items.
You can use .live for this.
Update
Since jQuery 1.7, the .on method is preferred way to do this.
Since jQuery 1.9 the .live method has been removed.