你能看看这个演示,让我知道我如何启用滚动到div从自动完成选定的项目?
$(document).ready(function () {
$('#tags').on('change', function () {
$('#tagsname').html('You selected: ' + this.value);
$('html,body').animate({
scrollTop: $("#"+ this.value).offset().top
});
}).change();
$('#tags').on('autocompleteselect', function (e, ui) {
$('#tagsname').html('You selected: ' + ui.item.value);
});
});
但是我得到这个错误
Uncaught TypeError: Cannot read property 'top' of undefined
代码在正确触发时工作。但是,只有当您为其中一个查找项输入与id匹配的值时,它才会正确触发。
根据Jquery的ID选择器文档:
对于id选择器,jQuery使用JavaScript函数document.getElementById(),它非常高效。
并按照文件的MDN。getElementById参数
- 元素是对element对象的引用,如果具有指定ID的元素不在文档中,则为null。
- id是一个大小写敏感的字符串,表示正在查找的元素的唯一id。
由于您的元素是用使用Proper Cased
字符串的id定义的,并且由于id查找是区分大小写的,如果您为Asp元素输入asp
,它将返回null
进行查找。
随后在null
上调用offset()
将返回undefined
。由于undefined
没有top
属性,您得到错误消息:
Uncaught TypeError: Cannot read property 'top' of undefined
所以解决方案是将你的id设置为某些case并使你的调用规范化。例如,如果你使用小写字母,那么:
$("#"+ this.value.toLower()).offset().top
或者更好的做法是做一些null检查等,以确保在开始对其调用方法之前确实有一个项目:
function getOffset(id){
if (this.value)
{
var matches = $("#"+ this.value.toLower());
if (matches.length){
return matches.offset().top;
}
}
return 0;
}
scrollTop: getOffset(this.value);
change
事件不存在,所以您的代码没有被触发。你必须这样做:
$(document).ready(function () {
$('#tags').on('autocompleteselect', function (e, ui) {
$('#tagsname').html('You selected: ' + ui.item.value);
$('html,body').animate({
scrollTop: $("#"+ this.value).offset().top
});
});
});
查看这个演示