Maybe I misunderstood the functions of .on() api of jQuery. Here is the code I am trying out:
http://jsfiddle.net/tugberk/Um9VE/
<a class="btn" href="#">foo</a>
<a href="#" class="new">New</a>
<script>
$(function(){
$("a.btn").on("click", function(){
alert("foo");
});
$("a.new").click(function(){
$("html").append($("<a/>").attr("class", "btn").attr("href", "#").text("bar"));
});
});
</script>
When I create a new a.btn element, the event is not auto-attached after the element is being created. I can achieve this with .bind() api easily by triggering it after I create the new button but one of my friends suggested me that .on() event is doing this automatically.
So, did I misunderstand the capabilities of .on() api?
For
.on()to work like.delegate()or.live()it requires a special syntax. The different kinds of ways you can use.on()/.off()are shown below, together with the old ways of doing it with.bind()/.live()and.delegate(), along with.undelegate()and.die().