Filling an array with numbers

I have this situation: There are 8 div blocks with identifiers such as "rateN_wrapper", where "N" is the number of divs:

<div id="rate1_wrapper">
  <a href="#" id="0_1">...</a>
  <a href="#" id="0_2">...</a>
  <a href="#" id="0_3">...</a>
</div>

<div id="rate2_wrapper">
  <a href="#" id="1_1">...</a>
  <a href="#" id="1_2">...</a>
  <a href="#" id="1_3">...</a>
</div>

...

var ratings = new Array();
for (i=0; i < 8; i++)
{
    ratings[i] = -1; // Default is unrated

}

for (i=0; i < 8; i++)
{
    $('#rate' + i + '_wrapper a').click(function() {
        ratings[i] = parseInt( $(this).attr('id').split('_')[1] );
        console.debug(ratings);
    });
}

My job is to populate the array in the right place using the click link identifier (parsed). But it always changes only the last element of the array (8). Why?

+3
source share
2 answers

This is a problem caused by closure in a for loop. You can find the identifier by analyzing the parent id:

for (i=0; i < 8; i++)
{ 
  $('#rate' + i + '_wrapper a').click(function() {
    var parentId = $(this).parent('div').attr('id');
    var index = /\d/.exec(parentId);
    ratings[index] = parseInt( $(this).attr('id').split('_')[1] );
  });
}
+2
source

i. . for 8, ratings[8]. , :

for (i=0; i < 8; i++)
{
    var idx = i;
    $('#rate' + idx + '_wrapper a').click(function() {
        ratings[idx] = parseInt( $(this).attr('id').split('_')[1] );
        console.debug(ratings);
    });
}

, var . , , idx . , , :

function CreateHandler(idx) {
    return function() {
        ratings[idx] = parseInt( $(this).attr('id').split('_')[1] );
        console.debug(ratings);
    }
}

for (i=0; i < 8; i++) {
    $('#rate' + idx + '_wrapper a').click(CreateHandler(i));
}

, , . idx .

+1

Source: https://habr.com/ru/post/1746264/


All Articles