简体   繁体   中英

Event Listener from for each works with just one child

okay so i'm bout to lose my hair have been trying to fix this all day long and always end with the same result ,

what am trying to do is getting data from firebase and that work just fine , the issue is i wanna click on the big box and then get the buttons value from the clicked box it works with the first box and never work with any other box .

function gotData(data) {

  // got data array
  all = data.val();
  var keys = Object.keys(all);
  if (keys === 'null') { return null;}
  for (var i = 0; i < keys.length; i++) {
    var k = keys[i] ;
    var color1 = all[k].color1;
    var color2 = all[k].color2;
    var color3 = all[k].color3;
    var color4 = all[k].color4;

    var output = '<div id="ProBox"><div id="myBox" class="bigBox animated fadeIn">'+
                      '<div class="top">'+
                        '<div class="box box1" style="background-color: '+ color1 +' "><button id="btnColor1" value="'+ color1 +'"></button></div>'+
                        '<div class="box box2" style="background-color: '+ color2 +' "><button id="btnColor2" value="'+ color2 +'"></button></div>'+
                      '</div>'+
                      '<div class="bootom">'+
                        '<div class="box box3" style="background-color: '+ color3 +' "><button id="btnColor3" value="'+ color3 +'"></button></div>'+
                        '<div class="box box4" style="background-color: '+ color4 +' "><button id="btnColor4" value="'+ color4 +'"></button></div>'+
                      '</div>'+
                    '</div></div>';

    body.innerHTML += output;

    var ProBox = document.getElementById('ProBox');

    Array.prototype.forEach.call(ProBox.children , function(box){
        box.addEventListener('click' , function(){
          console.log(this);
        })
    });

  }
  // end data array


};

any help appreciated cheers

我修复了buy querySelectorAll以选择所有框,然后使用for循环循环进入它们,效果很好

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM