gpt4 book ai didi

javascript - .top 从 jquery TypeScript 定义文件中丢失?

转载 作者:数据小太阳 更新时间:2023-10-29 04:46:31 26 4
gpt4 key购买 nike

我正在使用以下代码:

$('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top });

Typescript 给我一条错误信息:

The property 'top' does not exist on value of type 'Object'

我猜 jQuery 定义文件中缺少某些内容。有没有其他人看到过这个问题,或者这是 jQuery 通常不使用的东西?这是我以前从未见过的东西。

了解更多信息。这是使用它的代码:

   $.fn.buildTableOfContent = function () {
"use strict";
var h2 = this.find('h2');
if (h2.length > 0) {
var h1 = this.find('h1:first');
if (h1.length === 0) {
h1 = this.prepend('<h1>Help</h1>').children(':first');
}
var menu = h1.wrap('<div class="h1 with-menu"></div>')
.after('<div class="menu"><img src="/Content/images/menu-open-arrow.png" width="16" height="16"><ul></ul></div>')
.next().children('ul');
h2.each(function (i) {
this.id = 'step' + i;
menu.append('<li class="icon_down"><a href="#step' + i + '">' + $(this).html() + '</a></li>');
});
menu.find('a').click(function (event) {
event.preventDefault();
$('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top });
});
}
return this;
};

最佳答案

来自 jquery.d.ts 文件(我的版本中的第 374 行):

interface JQuery {
...
offset(): Object;
offset(coordinates: any): JQuery;
offset(func: (index: any, coords: any) => any): JQuery;
...
}

通过调用不带参数的函数,类型定义期望函数返回 Object 类型。我查看了 jQuery 的文档,您是对的,返回的对象应该具有 topleft 属性。

不幸的是,由于没有基于返回类型的重载这样的东西,您将无法在 JQuery 接口(interface)上添加另一个成员。因为,在这种特殊情况下,类型定义并不像它应该的那样具体,所以我建议简单地修改您的 jquery.d.ts 文件并更改返回类型,使其看起来如下(可能是字符串而不是数字?):

offset(): { top : number; left : number; };

如果你不想修改这个文件,你也可以选择在访问它的任何属性之前将结果转换为 any,例如:

$('html, body').animate({ scrollTop: (<any> $($(this).attr('href')).offset()).top });

缺点是每次调用不带参数的函数时都需要强制转换。

关于javascript - .top 从 jquery TypeScript 定义文件中丢失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13151776/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com