javascript - onClick event in a For loop -


i've tried create loop for, , increment onclick event, doesn't work.

a part of js :

 var gamecase = ['', '', '', '', '', '', '', '', ''], // 9     itemlists = $('game').getelementsbytagname('li'); // 9 items      for( var = 0; < itemlists.length; i++ ) {          // egal 9          itemlists[i].onclick = function() {               //          }     } 

but in case, loop finished before able click on element of list.

moreover, item list clicked , save on array. tried gamecase[this] (in onclick function), don't know if it's way.

john resig covers topic in "secrets of javascript ninja" ( http://ejohn.org/apps/learn/#59 )

you'll need create temporary scope preserve i's value

for ( var = 0; < itemlists.length; i++ ) (function(i){    itemlists[i].onclick = function() {       //   } })(i); 

edit:

var gamecase = ['', '', '', '', '', '', '', '', ''], // 9 $listparent = $('game').find('ul'), // li's parent itemlists = $('game').getelementsbytagname('li'); // 9 items  var listhandler = (function() {   var = 0;    return function() {     // $(this) in here refer clicked li     i++ // increment      if ( === 9 ) {       $listparent.off('click', 'li', listhandler); //remove eventhandler when reaches 9     }   } }());  $listparent.on('click', 'li', listhandler); // attach eventhandler ul element 

this should want, cant test right since i'm @ work.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -