I’m using jQuery’s .on() event handler and it’s only working when I use $(document).
This works:
$(function() {
$(document).on("click", ".search .remove", function(e) {
console.log("clicked");
});
});
This does not work:
$(function() {
$(".search .remove").on("click", function(e) {
console.log("clicked");
});
});
Nothing happens on that second one…no errors or anything. It just doesn’t fire.
You are using two different syntaxes of .on which have two very different outcomes.
Your first is:
This binds the event to context, and any events of type
eventthat gets to thecontextthat has ane.targetthat can be selected withtargetselectorwill trigger the handler withe.targetas the context. this is commonly known as event delegation.Your second syntax is
In this case, the event is bound directly to the elements currently on the page that match
targetselector, not future elements. This is essentially the same as the old.bind.