What am I doing wrong in this simple closure

it may be sleep deprivation, but I can not understand why this does not work. I want onclick to return the value I from the for loop that created this element and apply an event handler. Put it in close and it still rotates the maximum number of iterator.

window.onload = function(){
  var arbitrary_amount = 100;
  var the_list = document.getElementsByTagName('ul')[0];

  for(var i = 0; i < arbitrary_amount; i++){
    var natural_index = i + 1;
    var list_item = document.createElement('li');
    var inner_link = document.createElement('a');
    inner_link.setAttribute('href', '#');
    inner_link.innerHTML = "Link "+natural_index;

    inner_link.onclick = function(){
      return function(link_num){
        alert('You clicked link '+link_num);
      }(i);
    };

    list_item.appendChild(inner_link);
    the_list.appendChild(list_item);
  }


};
+3
source share
5 answers

you are using the closure in the wrong way ... I can’t give you an answer like the guru regarding what is actually happening, but the closure works here (did not check):

inner_link.onclick = (function(link_num){
   return function(){
       alert('You clicked link '+link_num);
   };
})(i);
+8
source

You can try:

window.onload = function(){
  var arbitrary_amount = 100;
  var the_list = document.getElementsByTagName('ul')[0];

  for(var i = 0; i < arbitrary_amount; i++){
    (function(){var natural_index = i + 1;
    var list_item = document.createElement('li');
    var inner_link = document.createElement('a');
    inner_link.setAttribute('href', '#');
    inner_link.innerHTML = "Link "+natural_index;

    inner_link.onclick = function(){
      return function(link_num){
        alert('You clicked link '+link_num);
      }(i);
    };

    list_item.appendChild(inner_link);
    the_list.appendChild(list_item);})();
  }


};
0
source

Firefox 3.5.5 Chrome 4.0.249.64.

0

, , onclick, . onclick, i.

, , , .

. MDC .

0
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">


<head>


<title>Just testing</title>


<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />


</head>
<body>



<div id="test1">
Testing
</div>




<script type="text/javascript">


//  self-invoking function


(function makeHR(){
      var newHR = document.createElement('hr');
      document.getElementById('test1').appendChild(newHR);
})();





function makeLink(j){


      var link =document.createElement("a");


  link.innerHTML ="<br>Link test " +j;


  link.setAttribute('href', '#');

  link.onclick = (function(link_num){


   return function(){


   alert('You clicked link '+link_num);

   };


  })(j);

  document.body.appendChild(link);
}


for (var i=1; i<4; i++) {

   makeLink(i);

}


</script>


</body>

</html>
0

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


All Articles