开发者

javascript looping through array and accessing key : value

I've looked through quite a few questions but can't figure this out:

I am strugling开发者_运维技巧 with some JS.

I have a config array for a form field character counter, like:

var charwatch = [
  {key: 'headline', value: 60}, 
  {key: 'subheading', value: 40}
];

It represents all the ID's of fields I want to watch, along with their corresponding max character counts.

The actual character counter / limiter works fine - the problem I am having is providing the above data to it.

I am trying to loop through that config and execute a function in each loop, passing key and 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, but I am finding that console.log(element) (in the .keyup function) is always "subheading", never "heading". So everything works exactly as it should for the subheading field, but not at all for the heading field.


You're running into a common issue that the variable is getting changed and when you later try and reference it it's the last reference, simple example:

for(var i=0; i<10; i++){
    $('#div-' + i).bind('click', function(){ alert(i); }) // will always be 10
}

You need to wrap the inner code in a function so that you create a new scope which saves the values of your variable:

for(var p in charwatch){
    (function( element, count ){
        var jq-element = '#' + element;
        ...
    })( charwatch[p].key, charwatch[p].value );
}

Or you can bind a closure:

$(jq-element).keyup(function( element, count ){
    return function() {
        check_max_chars(element, count); // external function   
        console.log(element);
    }
}( element, count ));

Alternatively, you can wrap your function in a with block, which also creates a closure. This, however, won't be 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
    }
}


Try this:

$.each(charwatch , function(a, b){
    $("#" + b.key).keyup(function() {     
        check_max_chars(b.key, b.value); // external function        
        console.log(b.key);   
    }); 
})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜