Assign click handlers in for loop

前端 未结 6 2126
野的像风
野的像风 2020-11-22 03:21

I\'m having several div\'s #mydiv1, #mydiv2, #mydiv3, ... and want to assign click handlers to them:

$(document).ready         


        
6条回答
  •  情话喂你
    2020-11-22 03:44

    It's a common mistake to create closures in loops in Javascript. You need to have some sort of callback function like this:

    function createCallback( i ){
      return function(){
        alert('you clicked' + i);
      }
    }
    
    $(document).ready(function(){
      for(var i = 0; i < 20; i++) {
        $('#question' + i).click( createCallback( i ) );
      }
    });
    

    Update June 3, 2016: since this question is still getting some traction and ES6 is getting popular as well, I would suggest a modern solution. If you write ES6, you can use the let keyword, which makes the i variable local to the loop instead of global:

    for(let i = 0; i < 20; i++) {
      $('#question' + i).click( function(){
        alert('you clicked ' + i);
      });
    }
    

    It's shorter and easier to understand.

提交回复
热议问题