您能看一下This Demo吗?让我知道如何启用自动完成滚动到所选项目的 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 documentation对于 ID 选择器:
For id selectors, jQuery uses the JavaScript function document.getElementById(), which is extremely efficient.
按照MDN对于 document.getElementById 参数
- element 是对 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 设置为某种大小写并规范您的调用。例如,如果您使用小写字母,则:
$("#"+ this.value.toLower()).offset().top
或者更好的是做一些空检查等,以确保在开始调用它的方法之前您确实拥有一个项目:
function getOffset(id){
if (this.value)
{
var matches = $("#"+ this.value.toLower());
if (matches.length){
return matches.offset().top;
}
}
return 0;
}
scrollTop: getOffset(this.value);
关于javascript - 添加滚动到 Div 功能以及 UI 自动完成功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32930364/