First of all, I will not search sources to substantiate what I will say.
First of all:
I wanted to at least do that:
$('.ident').click(function() {
alert($(this).val());
});
That would solve:
$('body').on("click", ".ident", function() {
alert($(this).val());
});
How to solve this problem?
The "base selector" for the event should already be loaded on the screen at the time you add the Listener, so just make an event bind to an element that is already on the screen and use the function parameters to make a sub-selection. (further explained below)
What I’m doing wrong?
You are adding a Listener to an element that is not yet present in the DOM at the time of execution.
Explanations:
When you add an event via Javascript, you are assigning an action to a particular element. If a new element, even with the same selector, is inserted into the DOM after the execution of this code, it will not be listening to this event.
In case, you added an event to class .ident
, however, only the elements with the class ident
that were already in the DOM at the time of execution the code would be linked to it.
Why use $('body').on('click', '.ident', function(){});
resolves?
In this case, the click event is being added to the element body, that is already in the DOM at the time of execution, what jQuery is doing behind this case, is basically: "after clicking inside the element body, checks if it was in the element that has a class ident
". In this way, the event is linked to the body, and not to the element with the class ident
, jQuery just confirms that the clicked element has the desired class, it does not keep any event linked to the class or other element (other than the body) in specific.
The first code does not work. Edit your answer and put only the second that works. It has the function of
.delegate()
which has been discontinued. When an element is added dynamically on the page, the second code works.– Sam