简体   繁体   English

Javascript全局数组对象无法读取

[英]Javascript global array object can't be read

I'm having a few issues and I think it is because of the way I'm declaring an array. 我遇到了一些问题,我认为这是因为我正在声明一个数组。 I'm using jQuery and I want to declare a global array so I can use its items inside my functions. 我正在使用jQuery,我想声明一个全局数组,所以我可以在我的函数中使用它的项目。 The way I'm doing it now, when I do try to use the items in a function, they are limited. 我现在这样做的方式,当我尝试使用函数中的项目时,它们是有限的。 I did a console log of the array and it seems to show that it has stuff in it (even the stuff that I want) but then when I perform jQuery functions on those items it tells me 我做了一个数组的控制台日志,它似乎表明它有内容(甚至是我想要的东西)但是当我在这些项目上执行jQuery函数时它告诉我

Cannot read property 'top' of undefined 无法读取未定义的属性“top”

Additionally, I've not used arrays much in JS, just in C++, so perhaps there's an issue with my syntax? 另外,我没有在JS中使用过很多数组,只是在C ++中,所以我的语法可能有问题吗? Here is a rough copy of the code I have: 这是我的代码的粗略副本:

var pigs = new Array();
pigs[0] = $('#foo');
pigs[1] = $('#bar');

$(document).ready(function(){
    console.log(pigs);
    var topCoord = pigs[0].offset().top;
});

I guess $('#foo') and $('#bar') both return empty jQuery objects. 我猜$('#foo')$('#bar')都返回空的jQuery对象。 You should wait for the DOM to be ready before querying it : 在查询之前,您应该等待DOM准备好:

var pigs = new Array();
$(document).ready(function(){
    pigs[0] = $('#foo');
    pigs[1] = $('#bar');
    console.log(pigs);
    var topCoord = pigs[0].offset().top;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM