Assign click handlers in for loop

前端 未结 6 2116
野的像风
野的像风 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:50

    Using on to attach the 'click' handler you can use the event data in order to pass your data like in:

    for(var i = 0; i < 20; i++) {
      $('#question' + i).on('click', {'idx': i}, function(e) {
        alert('you clicked ' + e.data.idx);
      });
    }
    

    //
    // let's creat 20 buttons
    //
    
    for(var j = 0; j < 20; j++) {
    	$('body').append($('

提交回复
热议问题