jquery - javascript looping through array and accessing key : value -
jquery - javascript looping through array and accessing key : value -
i've looked through quite few questions can't figure out:
i strugling js.
i have config array form field character counter, like:
var charwatch = [ {key: 'headline', value: 60}, {key: 'subheading', value: 40} ];
it represents id's of fields want watch, along corresponding max character counts.
the actual character counter / limiter works fine - problem having providing above info it.
i trying loop through config , execute function in each loop, passing key , value each time.
for(p in charwatch) { element = charwatch[p].key; jq-element = '#'+element; count = charwatch[p].value; $(jq-element).keyup(function() { check_max_chars(element, count); // external function console.log(element); }); }
it's kind of working, finding console.log(element) (in .keyup function) "subheading", never "heading". works should subheading field, not @ heading field.
you're running mutual issue variable getting changed , when later seek , reference it's lastly reference, simple example:
for(var i=0; i<10; i++){ $('#div-' + i).bind('click', function(){ alert(i); }) // 10 }
you need wrap inner code in function create new scope saves values of variable:
for(var p in charwatch){ (function( element, count ){ var jq-element = '#' + element; ... })( charwatch[p].key, charwatch[p].value ); }
or can bind closure:
$(jq-element).keyup(function( element, count ){ homecoming function() { check_max_chars(element, count); // external function console.log(element); } }( element, count ));
alternatively, can wrap function in with
block, creates closure. this, however, won't supported in js strict mode
or es5 (i.e. future versions of javascript):
for(p in charwatch) { with({ element : charwatch[p].key, count : charwatch[p].value }){ // existing code } }
javascript jquery arrays
Comments
Post a Comment