Reputation: 333
I have experience using angular and jquery. In jquery i have often used selector like this:
<input name="name" class="cls">
<input name="age" class="cls">
$('.cls').change(function(){ });
My Question is how is this implemented by jquery. How does it know when the value of an input changes. When jquery encounters this selector, will it go to all the classes containing this and add onchange event to make html like this?
<input name="name" class="cls" onchange="func_ref()">
<input name="age" class="cls" onchange="func_ref()">
Knowing this will help me better optimize frontend javascript. Lately i learned that Angular is truly magic but comes at the cost of performance.
Upvotes: 1
Views: 17290
Reputation: 129079
Yes, $('.cls').change(function() { /* ... */ })
will get all of the elements that currently have the class cls
applied and attach an event listener to them, although it does it through addEventListener
, rather than by adding an attribute.
If you have lots of elements, there’s sometimes a way you can avoid attaching large numbers of event listeners. Namely, due to event bubbling, for certain events you can add an event listener to a common parent element, and the browser takes care of bubbling the event up from the actual originating element. jQuery offers a handy way of utilizing this mechanism while still being selective in what originating elements you care about, like this:
$('#container').on('change', '.cls', function() { /* ... */ });
…which actually attaches a listener to #container
, but will act as if you added a listener to all elements matching .cls
.
Upvotes: 2
Reputation: 1
When jquery encounters this selector, will it go to all the classes containing this and add onchange event to make html like this?
Yes change
event attached to all elements having selector class
; though onchange="func_ref()"
not inserted into html
. Inside handler func_ref
this
references DOM
element where change
event occurred.
Upvotes: 0