我有以下代码,使我可以滚动到我的网页上的位置。然而,当我使用严格的,我得到以下错误:使用严格抛出错误
类型错误:未定义不是对象(评估 'refElement.position()上面。') (匿名函数)主要:34
的ReferenceError:能找不到变量:$ target (匿名函数)main.js:17
请有人可以解释为什么它不起作用,当我使用严格,当我评论它呢?我如何使它起作用?
感谢
代码:
'use strict';
$(document).ready(function() {
$(document).on("scroll", onScroll);
//smoothscroll
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
$(document).off("scroll");
$('a').each(function() {
$(this).removeClass('active');
})
$(this).addClass('active');
var target = this.hash,
menu = target;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top+2
}, 500, 'swing', function() {
window.location.hash = target;
$(document).on("scroll", onScroll);
});
});
});
function onScroll(event){
var scrollPos = $(document).scrollTop();
$('#menu-center a').each(function() {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
$('#menu-center ul li a').removeClass("active");
currLink.addClass("active");
}
else{
currLink.removeClass("active");
}
});
}
你知道什么''严格使用';'吗?整个问题是要找出错误。 – Pointy
尝试使用'var $ target' ...错误告诉你 – charlietfl
错误信息的哪部分你不明白? – SLaks