Assign click handlers in for loop

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

    You can get by with assigning the click handler once (or at least not making many unnecessary closures). Put all the divs in one class mydivs, then:

    $(document).ready(function(){
        $('.mydivs').click(function(){
            // Get the number starting from the ID's 6th character
            // This assumes that the common prefix is "mydiv"
            var i = Number(this.id.slice(5));
    
            alert('you clicked ' + i);
        });
    });
    

    This looks at the element's ID to get its number, using the slice string method to strip the initial letters off.

    Note: It may be better to use

    $('#divcontainer').on('click', '.mydivs', function(){
    

    instead of

    $('.mydivs').click(function(){
    

提交回复
热议问题