0

just try to run this code in two ways:

1) run this code below; 2) enable for loop then run it

<html>
<head>
<script>
    function toggle(){
        //console.log('hi');

        var samplediv = document.getElementById('samplediv');
        samplediv.innerHTML = '';

        var i = 1;
        //for(var i = 0; i < 3; ++i){
            samplediv.innerHTML +=
                "<div id=\'jh"+ i + "\'>Hi This is "+i+"</div>" +
                "<div id=\'edit"  + i +  "\' style=\'display:none\'>Edit "+i+"</div>" ;
                document.getElementById('jh'+i).addEventListener("click", function(){document.getElementById('edit'+i).style.display="block";});
            /*
            (function(i){
                //console.clear();
                var key = i;
                i += "";
                document.getElementById('jh0').addEventListener("click", function(){document.getElementById('edit0').style.display="block";});
                //document.getElementById('jh'+key).addEventListener("click", function(){document.getElementById('edit'+key).style.display="none";}, true);
                //console.log(i, key);
            }(i));
            */
        //}
    }
</script>
</head>
<body>
<div id="samplediv" >over here</div>

<script>toggle();</script>
</body>

</html>

I'm trying to add addEventLister on every divs using for. I'm sure this is kind of call by reference error. I know there are ways to add events such as on attribute method. Also adding a number of similar listeners is inefficient but I have to make them as you can see.

I've made a IIFE to make key be a value but failed. Do you have any idea to solve this problem?(No jQuery please)

  • You don't clearly explain how your code is failing, but this is possibly a duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – apsillers Mar 06 '15 at 15:28
  • Thanks for a help but that is not the answer for this. – Kim Jihyeong Mar 06 '15 at 15:42

1 Answers1

1

JSFiddle

  1. You will change method which You use to adding new elements. I replaced innerHTML += to document.createElement for each new item.

    var jh = document.createElement('div');
    jh.id = 'jh'+i;
    jh.innerText = 'Hi This is '+i;
    
    var edit = document.createElement('div');
    edit.id = 'edit'+i;
    edit.style.display = 'none';
    edit.innerText = 'Edit '+i;
    
    samplediv.appendChild(jh).appendChild(edit);
    
  2. Variable i on click event is visible with last value, so You must get index from other source (from id for example).

    document.getElementById('jh'+i).addEventListener("click", function(){
    
        var jhIndex = this.id.split('jh')[1];
        document.getElementById('edit'+jhIndex).style.display= 'block';
    });
    
Mateusz Mania
  • 839
  • 4
  • 15