onClick event in a For loop

后端 未结 4 1080
误落风尘
误落风尘 2020-12-01 14:48

I\'ve tried to create a loop with a for, and increment by an onclick event, but it doesn\'t work.

A part of js :

 var gameCase = [\'\', \'\', \'\', \         


        
相关标签:
4条回答
  • 2020-12-01 15:06

    Sorry if I did not understand your question properly, From the code I understand that, you are trying to add an onclick handler to all the list elements in found in the game tag (perhaps it should be a class / id).

    The for loop will be executed when the script tag / file loads without any user interaction.

    If you wish to assign a function that uses the current value of the counter. Use the following code:

    itemLists[i].onclick = (function() {
        return function() {
             // TODO ---
            // Your handler code here
    }
    })();
    
    0 讨论(0)
  • 2020-12-01 15:14

    Another option is to use a forEach loop this creates a new variable for each iteration.

    var gameCase = ['', '', '', '', '', '', '', '', ''], // 9
    itemLists = $('game').getElementsByTagName('li'); // 9 items
    
    itemLists.forEach(function(item,index){
        item.onclick = function() {
          // do something
     }
    });
    
    0 讨论(0)
  • 2020-12-01 15:15

    John Resig covers this topic very well in "Secrets of the JavaScript Ninja" ( http://ejohn.org/apps/learn/#59 )

    You'll need to create a temporary scope to preserve i's value

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

    Edit:

    var gameCase = ['', '', '', '', '', '', '', '', ''], // 9
    $listParent = $('game').find('ul'), // li's parent
    itemLists = $('game').getElementsByTagName('li'); // 9 items
    
    var listHandler = (function() {
      var i = 0;
    
      return function() {
        // $(this) will in here refer to the clicked li
        i++ // increment i
    
        if ( i === 9 ) {
          $listParent.off('click', 'li', listHandler); //remove eventhandler when i reaches 9
        }
      }
    }());
    
    $listParent.on('click', 'li', listHandler); // attach eventhandler to ul element
    

    This should do what you want, cant test it right now since I'm at work.

    0 讨论(0)
  • 2020-12-01 15:27

    Wrap your listener:

    onclick = (function(i) {return function() {
        ...
    };})(i);
    

    This fixes your variable scope issues.

    0 讨论(0)
提交回复
热议问题