I was once learned it is "better" to limit the use of global selectors. I tried it in the code below, but it doesn't work because the content (flat HTML) is loaded trough AJAX. The browser now has no clue what $(".item") is, because it is not loaded yet. What is the best way to solve this? Use a global selector like I did in the last snipper, or something else?
export default class overview {
constructor(el) {
this.loadOverview(el);
}
loadOverview(el) {
const $this = $(el),
overview = $('.js-overview', $this),
item = $('.js-item', $this)
// Fetch content
$.ajax({
url: "URL",
type: 'GET',
success: function (data) {
$(overview).append(data);
}
});
$(".item").click(function() {
// Do something doesn't work
}
}
Clicking on item now doesn't do anything, because the item can't be found. When i change it to
$body.on('click', '.item', function () {
// Do something works
});