I'm trying to access the data-id of my div on click. The domain models are projects and todos for users. This is my current implementation (working):
// script-tag bottom of user-page.html, before footer include (jinja2)
const projects = '{{projects | count}}';
for (let i = 1; i <= projects; i++) {
const click_id = `#clickable-${i}`;
$(click_id).on("click", () => {
const data = $(click_id).data();
redirectToProjectPage(data);
});
}
and html:
{% for project in projects %}
<div id="clickable-{{loop.index}}" data-id="{{project.id}}" style="display:inline-block;">
... stuff.
</div>
{% endfor %}
Now I've tried to implement the refactoring by using jQuery.each and jQuery.on by browsing SO and referencing jQuery documentation, but following code produces undefined for me. Note: in the html I swapped the id for a class of "clickable".
$('.clickable').each(() => {
const $this = $(this);
$this.on('click', () => {
const id = $(this).data('id')
console.log(id) // produces undefined
redirectToProjectPage(id)
});
});
How do I proceed?