Javascript 未捕获类型错误:无法读取属性';顶部';未定义的
我得到了这个错误Javascript 未捕获类型错误:无法读取属性';顶部';未定义的,javascript,jquery,Javascript,Jquery,我得到了这个错误 $.fn.scroller = function(targetid){ this.on('click', function(event) { var target = $("#" + this.getAttribute('data-scroll')); $('html, body').animate({scrollTop: target.offset().top}, 1000); }); return this;};
$.fn.scroller = function(targetid){
this.on('click', function(event) {
var target = $("#" + this.getAttribute('data-scroll'));
$('html, body').animate({scrollTop: target.offset().top}, 1000);
});
return this;};
offset
返回undefined
的唯一原因是如果您在一个空的jQuery集合上调用它。显然,$(“#”+this.getAttribute('data-scroll'))
返回了一个空集
您将需要添加一个防护。事实上,我可能会添加两个:
$.fn.scroller = function(targetid) {
this.on('click', function(event) {
var id = this.getAttribute('data-scroll') || ""; // ***
if (id) { // ***
var target = $("#" + id);
if (target[0]) { // ***
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
} // ***
}
});
return this;
};
或者更简洁有效地:
$.fn.scroller = function(targetid) {
this.on('click', function(event) {
var id = this.getAttribute('data-scroll');
var target = id && document.getElementById(id);
if (target) {
$('html, body').animate({
scrollTop: $(target).offset().top
}, 1000);
}
});
return this;
};
target.offset()。这取决于你找到原因。谢谢…它起作用了