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.
You could do this:
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 theibeing what it was at the end of thefor()loop and your function getting the last element of that array.