[英]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]+'"]');
});
};
单击该元素时, i
将增加到anchors.length
的值。
您的点击处理程序引用了i
。
JavaScript中未解析的属性查找返回undefined
。
使用this
作为元素的引用会容易得多。 否则,找到一个方法来传递的价值i
的价值,而不是直接引用它。
你未定义的原因是因为i
实际上等于5
。 看看这个:
for ( var i = 0; i < 5; i++ ) {
console.log( i );
}
现在在循环完成之后你会认为i
在这个时间点是未定义的,因为它应该是for
循环的本地。 不幸的是,这种情况并非如此。 一种简单的测试方法:
for ( var i = 0; i < 5; i++ ) {
console.log( i );
}
console.log( i ) // Logs out 5;
简而言之,for循环的i++
在真实测试部分之后执行, i < 5
位。 因此,当i
等于4
,循环运行,然后它会增加i++
,它将i
的值设置为5,这反过来又无法通过真值测试。
所以现在你知道i
等于5
,当你在anchors
数组中进行查找时, anchors[5]
是未定义的。
这很重要的原因是因为每次单击事件触发时,它都将执行i
的缓存值为5,反过来,您将始终记录undefined
要解决这个问题,我们可以像这样创建一个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 );
};
变量i
得到了最后一个循环的值。 如果要访问锚点,可以使用:
console.log($(this).attr('href').substr(1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.