How to access the dynamic targets when using jQuery.fn.on with dynamic selectors?
Because $(this) is giving the parent element inside binder function.
And I need to get each element itself to fetch corresponding data-attributes dynamically.
Fiddle: https://jsfiddle.net/u1kuufj7/1/
HTML:
<div id="container">
<div id="1" class="ch">Click</div><br>
<div id="2" class="ch">Click</div><br>
<div id="3" class="ch">Click</div><br>
<div id="4" class="ch">Click</div><br>
<div id="5" class="ch">Click</div><br>
</div>
Javascript:
var $container = $('#container');
var $chs = $('.ch');
$container.on('click', $chs, function() {
alert($(this).attr('id'));
});
To use event delegation, the second argument to
onshould be a selector (a string), not a jQuery object:Now,
thiswill refer to the.chthat was clicked.Live Example:
Side note:
$(this).attr("id")is just a long way to writethis.id.Side note 2: While
idvalues starting with digits are perfectly valid, they're awkward to work with in CSS, since ID selectors can't start with a literal digit. (There are ways around it, via escaping or via attribute selectors, but it's awkward.) For that reason, I usually avoidids starting with digits.