javascript - onClick on loop elements -


i need add onclick event loop elements:

<div id="try"><div/> <div id="boxes"><div/>  <script>  var x=1; var boxes=[]; while(x<=7){ boxes[x++]=['<div class="colorbox">whatever now, because  colored boxes</div>'];} document.getelementbyid("boxes").innerhtml=boxes;  var = document.getelementsbyclassname('colorbox'); document.write(i); i.onclick = function(){doit(1, 2);}  function doit(a, b){     document.getelementbyid("try").innerhtml=a + b;} <script> 

i don't know why onclick event doesn't work in example. console doesn't give mistakes. wrong? 'document.write(i)' shows, var nor empty nither undefinited. it's html object.

document.getelementsbyclassname() uses plural "elements" , hence returns array. if there single element matches class selector, return array 1 element.

hence, need attach handler element itself, rather entire array. you've tagged question jquery, i'd suggest using jquery (which attach handler each element in array):

var x=1; var boxes=[]; while(x <= 7) {     boxes[x++] = ['<div class="colorbox">whatever now, because  colored boxes</div>']; }  document.getelementbyid("boxes").innerhtml = boxes;  var = document.getelementsbyclassname('colorbox');  document.write(i);  $(i).on('click', function () {   doit(1, 2); });  function doit (a, b) {     document.getelementbyid("try").innerhtml = + b; } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -