Evaluation of jQuery function variable value during definition of that function
-
02-10-2019 - |
Question
I have a large number of rows in a table within which I wish to attach a unique colorpicker (jQuery plugin) to each cell in a particular column identified by unique ids. Given this, I want to automate the generation of instances of the colorpicker as follows:
var myrows={"a","b","c",.....}
var mycolours={"ffffff","fcdfcd","123123"...}
for (var i=0;i<myrows.length;i++) {
$("#"+myrows[i]+"colour").ColorPicker({flat: false,
color: mycolours[i],
onChange: function (hsb, hex, rgb) {
$("#"+myrows[i]+"currentcolour").css('backgroundColor', '#' + hex);
}
});
Now this doesn't work because the evaluation of the $("#"+myrows[i]+"currentcolour") component occurs at the time the function is called, not when it is defined (which is want I need).
Given that this plugin javascript appends its code to the level and not to the underlying DOM component that I am accessing above so can't derive what id this pertains to, how can I evaluate the variable during function declaration/definition?
Thanks for any help/insight anyone can give.
Brian.
Solution
You could do this:
$.each(myrows, function(i, row) {
$("#"+row+"colour").ColorPicker({flat: false,
color: mycolours[i],
onChange: function (hsb, hex, rgb) {
$("#"+row+"currentcolour").css('backgroundColor', '#' + hex);
}
});
});
The $.each()
function creates a closure, so the variable you're passing in (row
) is it's own copy scoped correctly for what you want here, instead of the i
being what it was at the end of the for()
loop and your function getting the last element of that array.