开发者

jQuery / Javascript error: myvar[i] is undefined

Why am I getting this error?

jQuery(document).ready(function($){

  $('.stuff').each(function(){

    function thing(id, count){
      this.id = id;      
      this.count = count;
    }

    var myvar = new Array();
    my开发者_Go百科var.push(new thing('one', '134'));
    myvar.push(new thing('two', '225'));


    $('a', this).click(function(event){
       var i = $(this).attr('class'); // class is 'one', 'two' etc...
       // myvar[i] appears undefined here! wtf?

    });    
  });  

});


You're trying to access an index based (0,1,2) array with a string index (i, the result of attr('class')).

Easiest fix is to use an object (aka fake hash array) for myvar and set the keys to the class names.

var myvar = {
  one : 134,
  two : 225
};

With that myvar, you can still use myvar[i] with i being the string index (one, two...)


What is the value of "i"? I suspect you are not getting a myvar = null, but myvar[0] = null because you have not added any data to the array.

Can you include the script within the anonymous function.


As i said , your value i might be wrong ,

it should start with 0,1,2 et .... print the value or alert and check it

$('a', this).click(function(event){
       var i = $(this).attr('class'); // class is 'one', 'two' etc...
       // myvar[i] appears undefined here! wtf?

    });    
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜