Why does the <a>
trigger in my case?
The event is simply being triggered because you are attaching the click
event listener after appending the anchor element to the DOM.
In other words, $('a').click(function() {...});
will attach the click
event listener to all a
elements that exist in the DOM at that time.
Since the a
element has already been appended, the click
event listener is attached.
I thought I have to use binding like .on()
for incoming elements
You only need to delegate the event listener if you are attaching an event listener before the element exists in the DOM.
For instance, if you were to reverse the logic and append the element directly after attaching the event listener, it simply wouldn't work:
// This wouldn't be fired since the element is
// appended after the event listener is attached
$('a').click(function() {
alert('trigger <a>!');
});
$('div').append('<a>link</a>');
Which is why you would need to delegate the event listener to an ancestor element that does exist in the DOM at that time:
$('div').on('click', 'a', function() {
alert('trigger <a>!');
});
$('div').append('<a>link</a>');