JQuery myArray[myVarriable] 未定义,即使我已经定义了它
好吧,让我告诉你我想在这里做什么, 有 4 个对象,与此类似:
var links = {name: "Links", id: "links", index: 0};
我将它们放在一个数组中:
var pages = [links,about,projects,contact];
我创建了这个函数:
function active_page(selected){
var active = 0;
$("[id="+pages[selected].id+"]").show();
}
然后我运行 active_page(0) in
$(function(){
active_page(active);
});
并且我收到此错误:
pages[selected] is undefined
整个 .js 文件在这里: http://pastebin.com/2rBWiVJF
我收到的错误位于第 26 行,
谢谢您的宝贵时间
Ok, let me show you what im trying to make here,
There are 4 objects, similar to this one:
var links = {name: "Links", id: "links", index: 0};
I place them inside an array:
var pages = [links,about,projects,contact];
I created this function:
function active_page(selected){
var active = 0;
$("[id="+pages[selected].id+"]").show();
}
Then i run active_page(0) in
$(function(){
active_page(active);
});
And im getting this error:
pages[selected] is undefined
The whole .js file is here:
http://pastebin.com/2rBWiVJF
The error im getting is in line 26
Thank you for your time
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个常见问题。实际问题在于您的
clicked()
函数。for
循环不会创建新的作用域,因此您始终引用相同的i
变量,该变量将在循环后保存最新值。在 JavaScript 中确定变量作用域的唯一方法是在函数中。因此,您应该将
i
传递给新函数调用以确定其作用域。This is a common problem. The actual issue lies in your
clicked()
function.The
for
loop doesn't create a new scope, so you're always referring to the samei
variable, which will hold the latest value after the loop.The only way to scope a variable in JavaScript is in a function. So you should pass
i
to a new function invocation in order to scope it.