Corbee Corbee - 12 days ago 12
Javascript Question

Why is my Loop event not working?

I'm trying to set the node sharedobject to trigger for each a href click event, but for some reasons, only the first one is working. What am I doing wrong?

for (let i = 0; i < files.length; i++) {
file_container.innerHTML = file_container.innerHTML + `<a id="file${i}" href="#" class="list-group-item">${files[i]}</a>`;
document.getElementById('file' + i).onclick = (function (i) {
require('electron').remote.getGlobal('sharedObject').filename = files[i].replace('.tnb','');
window.location = "login.html";
})(i);
}

Answer

the onclick assignment should accept a function but what your code is doing is (immediately) executing a function and then returning the result of this execution to onclick.

Since you're using let, which has block scope, there's no need to use an IIFE, you can just return a function as the handler, not execute it:

for (let i = 0; i < files.length; i++) {
  file_container.innerHTML = file_container.innerHTML + `<a id="file${i}" href="#" class="list-group-item">${files[i]}</a>`;
  document.getElementById('file' + i).onclick = function () { // <-- return the click handler for each element
    require('electron').remote.getGlobal('sharedObject').filename = files[i].replace('.tnb','');
    window.location = "login.html";
  };
}

As suggested by Alnitak in the comments, using forEach would create a separate scope and eliminate the need for the IIFE:

files.forEach(function (file, i) {
  file_container.innerHTML = file_container.innerHTML + `<a id="file${i}" href="#" class="list-group-item">${file}</a>`;
  document.getElementById('file' + i).onclick = function () {
    require('electron').remote.getGlobal('sharedObject').filename = file.replace('.tnb','');
    window.location = "login.html";
  };
});