0

In case of:

    var allBusiness = ["one", "two", "three", "four"]
    for (var i = 0; i < allBusiness.length; i++) {
    document.getElementById(allBusiness[i]).addEventListener("click", function () {
        console.log(allBusiness);
    });
}

This one logs ["one", "two", "three", "four"]

However the following one where I try to log each value separately shows undefined:

    var allBusiness = ["one", "two", "three", "four"]
    for (var i = 0; i < allBusiness.length; i++) {
    document.getElementById(allBusiness[i]).addEventListener("click", function () {
        console.log(allBusiness[i]);
    });
}

why doesn't what log the corresponding names? and how to achieve that?

Jo Hannes
  • 55
  • 2
  • 10

1 Answers1

0

The reason is simple: i is no longer defined in the scope of the callback function you are passing through.

As for how, i think a good question to ask, what are you trying to achieve? You can just use this.

var allBusiness = ["one", "two", "three", "four"]
for (var i = 0; i < allBusiness.length; i++) {
    document.getElementById(allBusiness[i]).addEventListener("click", function () {
        console.log(this.id);
    });
}

p.s. note: I do not think this is a good way to solve the problem, but it'll get what you want

Daemedeor
  • 1,013
  • 10
  • 22