Linking to a function that has non-link parameter values

I am not sure exactly how to describe what I want. I want to define a function with parameters that are local VALUE, not a reference.

say I have a list of objects that I want to create

for(i = 0; i < 10; i++){
  var div = document.createElement("div");
  div.onclick = function(){alert(i);};
  document.appendChild(div);
}

Now I believe in this example, no matter which div I click, it will warn "10"; since this is the last value of the variable i;

Is there any way / how can I create a function with parameters being the value that they have at the moment when I specify the function ... if that makes sense.

+3
source share
2 answers

You need to create a function inside another function.

For instance:

div.onclick = (function(innerI) {
    return function() { alert(innerI); }
})(i);

, , . , .

, :

function buildClickHandler(i) {
    return function() { alert(i); };
}

for(i = 0; i < 10; i++){
    var div = document.createElement("div");
    div.onclick = buildClickHandler(i);
    document.appendChild(div);
}
+5

:

for(i = 0; i < 10; i++){
    (function(i){
        var div = document.createElement("div");
        div.onclick = function(){alert(i);};
        document.appendChild(div);
    })(i)
}
0

Source: https://habr.com/ru/post/1737071/


All Articles