var el = $('.container');
var anchors = new Array('jobs', 'portfolio', 'docs', 'interier', 'price');
for (var i = 0; i < anchors.length; i++) {
el.on('click', 'a[href$="#'+anchors[i]+'"]', function (e) {
e.preventDefault();
console.log(anchors[i]);
$.scrollTo('a[name="'+anchors[i]+'"]');
});
};
1
A
回答
3
当您单击该元素时,i
将递增到值anchors.length
。
您的点击处理程序有对i
的引用。
JavaScript中未解决的属性查找返回undefined
。
使用this
作为元素的引用会容易得多。否则,找到一种方法来通过值来传递值i
,而不是直接引用它。
1
您未定义的原因是因为i
实际上等于5
。看看这个:这个循环完成后
现在你会认为i
将在这个时间点是不确定的,因为它应该是本地的for
循环。不幸的是,这种情况并非如此。一个简单的方法来测试这一点:
for (var i = 0; i < 5; i++) {
console.log(i);
}
console.log(i) // Logs out 5;
简而言之,的的i++
for循环获取真相测试部分执行后,将i < 5
位。因此,当i
等于4
时,循环运行,之后它会增加i++
,该值将i
的值设置为5,这反过来不能通过真值测试。
所以现在你知道i
等于5
,当你在你的anchors
数组中查找时,anchors[5]
是未定义的。
的原因,这是很重要的,因为每一次点击事件触发,它会为i
这是5,反过来,你将永远记录未定义
为了解决这个问题,我们可以创建执行缓存值别名的i
价值,像这样
var el = $('.container');
var anchors = new Array('jobs', 'portfolio', 'docs', 'interier', 'price');
for (var i = 0; i < anchors.length; i++) {
// By passing the value to this self executing function,
// it creates a new instance of the variable
(function (index) {
el.on('click', 'a[href$="#'+anchors[index]+'"]', function (e) {
e.preventDefault();
console.log(anchors[index]);
$.scrollTo('a[name="'+anchors[index]+'"]');
});
})(i);
};
0
变量i
拿到了最后一个循环的价值。如果您要访问的锚,你可以使用这个:
console.log($(this).attr('href').substr(1));
相关问题
- 1. 为什么console.log(true && undefined)返回undefined而if(true && undefined)返回false?
- 2. 为什么console.log函数返回undefined?
- 3. 为什么这段代码返回undefined?
- 4. 为什么这段代码返回undefined?
- 5. CONSOLE.LOG返回undefined
- 6. Console.log返回'undefined'
- 7. 为什么此代码返回'复杂'?
- 8. 为什么JSON.stringify返回undefined
- 9. 为什么innerHTML返回'undefined'?
- 10. 为什么fs.readdir返回`undefined`?
- 11. 为什么我返回undefined?
- 12. 为什么string.length返回undefined?
- 13. 为什么val()返回undefined?
- 14. 为什么这返回undefined?
- 15. FileReader返回“undefined”。为什么?
- 16. 为什么setState返回undefined?
- 17. 为什么req.params返回'undefined'?
- 18. 为什么event [1]返回undefined,但console.log(event)似乎返回一个数组?
- 19. 为什么我的javascript代码返回TypeError undefined?
- 20. 为什么这段代码总是返回undefined?
- 21. 为什么在此代码中append不返回任何值?
- 22. 为什么ATOI在此代码中返回0?
- 23. 为什么innerHTML在angularjs中返回undefined
- 24. 为什么此代码返回没有ViewName的视图结果?
- 25. 为什么此Ruby代码不会返回预期的答案?
- 26. 为什么此代码返回“不支持指定的方法”。
- 27. AngularJS - 简单$范围的console.log()返回undefined
- 28. 为什么此代码将文本设置为undefined?
- 29. 为什么我的ASP.NET AutoCompleteExtender返回undefined?
- 30. 为什么我的函数返回undefined?
有点儿offtopic:初始化像变种锚=阵列[“一”,“B”,“C”]应该是[使用Javascript封闭更快 – DVM 2013-03-21 10:05:53
可能重复内部循环 - 简单的实际例子](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – 2013-03-21 10:12:29
错误的范围,我没有在那里定义。 – 2013-03-27 23:41:10