Jquery can't get my head around this

前端 未结 4 759
予麋鹿
予麋鹿 2021-01-20 04:26

The alert(i) onclick bind line is run on 3 divs, but all of them when clicked alert the last set value of i. I hope what I\'m trying to do makes s

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-20 04:50

    While you could use invoke a function inside the loop, creating a new variable scope which captures the current value of i, an alternate approach would be to simply take the i value from the element's ID attribute:

    for (var i = 0; i < self.bars[BarsIndex].markers.length; i++) {
    
        $("#bmi-" + self.containerId + "-" + i).bind('click', function() {
              //grab the number from the ID of the element
            alert( /\d+$/.exec( this.id )[0] );
        });
    }
    

    Example: http://jsfiddle.net/UGQA7/

提交回复
热议问题