[英]Why console.log in this code return undefined?
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]+'"]');
});
};
When you click that element, i
will have been incremented to the value of anchors.length
. 单击该元素时, i
将增加到anchors.length
的值。
Your click handler has a reference to i
. 您的点击处理程序引用了i
。
An unresolved property lookup in JavaScript returns undefined
. JavaScript中未解析的属性查找返回undefined
。
It would be much easier to use this
as a reference to the element. 使用this
作为元素的引用会容易得多。 Otherwise, find a way to pass the value of i
by value, not a direct reference to it. 否则,找到一个方法来传递的价值i
的价值,而不是直接引用它。
The reason you are getting undefined is because i
is actually equal to 5
. 你未定义的原因是因为i
实际上等于5
。 Take a look at this: 看看这个:
for ( var i = 0; i < 5; i++ ) {
console.log( i );
}
Now after that loop has completed you would think that i
would be undefined at this point in time because it should be local to the for
loop. 现在在循环完成之后你会认为i
在这个时间点是未定义的,因为它应该是for
循环的本地。 Unfortunately, this is not the case. 不幸的是,这种情况并非如此。 A simple way to test this: 一种简单的测试方法:
for ( var i = 0; i < 5; i++ ) {
console.log( i );
}
console.log( i ) // Logs out 5;
Put simply, the i++
of the for loop gets executed after the truth test part, the i < 5
bit. 简而言之,for循环的i++
在真实测试部分之后执行, i < 5
位。 So when i
is equal to 4
, the loop runs, and afterwards it gets incremented by i++
, which sets the value of i
to 5, which in turn fails the truth test. 因此,当i
等于4
,循环运行,然后它会增加i++
,它将i
的值设置为5,这反过来又无法通过真值测试。
So now that you know i
is equal to 5
, when you do the lookup in your anchors
array, anchors[5]
is undefined. 所以现在你知道i
等于5
,当你在anchors
数组中进行查找时, anchors[5]
是未定义的。
The reason this is important is because every time a click event fires, it will execute the cached value for i
which is 5, and in turn, you will always log undefined 这很重要的原因是因为每次单击事件触发时,它都将执行i
的缓存值为5,反过来,您将始终记录undefined
To fix this, we can create an alias to the value of i
like so 要解决这个问题,我们可以像这样创建一个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 );
};
The variable i
got the value of the last loop. 变量i
得到了最后一个循环的值。 If you want to access the anchor you can use this: 如果要访问锚点,可以使用:
console.log($(this).attr('href').substr(1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.