0

I have a little problem here. My console.log(e) gives me the good result (1 or 2).

but the console.log(test) return me the integer variable. how can I store the function result in the test variable to use it later please ? Thx a lot !

const spans = selectPager.getElementsByTagName('span');

const test = function() {
  for (let i = 0, len = spans.length; i < len; i++) {
    (function(e) {
      spans[i].onclick = function() {
        console.log(e)
      }
    })(i);
  }
}
test();

console.log(test);
Andreas
  • 21,535
  • 7
  • 47
  • 56
Stéphan E
  • 31
  • 3
  • Your function doesn't seem to be returning anything. Could you explain what you want to store? – Shadab Feb 09 '21 at 14:39
  • If you use a snippet then please also use the _"Tidy"_ button before you close the editor – Andreas Feb 09 '21 at 14:42
  • I want to store the result of the console.log(e). spans[i].onclick = function(){ console.log(e) Sorry i'm a complete beginner :). – Stéphan E Feb 09 '21 at 14:44
  • You can't store a value in `test` when you click the span that *travels back in time* (!!) so it is available to the `console.log(test)` you have at the bottom of your code. – Quentin Feb 09 '21 at 14:45

1 Answers1

0

Pass a callback to test, and invoke the callback inside the click handler. There's also no need for the IIFE inside the loop, since you're using let:

const spans = document.getElementsByTagName('span');


const test = function(cb) {
  for (let i = 0, len = spans.length; i < len; i++) {
    spans[i].onclick = function() {
      console.log(i)
      cb(i);
    };
  }
}
test((result) => {
  console.log('Outside, have', result);
});
<span>click</span>
<span>click</span>
<span>click</span>
<span>click</span>
<span>click</span>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320