从jquery TypeScript定义文件中缺少.top?

时间:2012-10-31 05:29:14

标签: javascript jquery typescript

我使用以下代码:

$('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;
    };

2 个答案:

答案 0 :(得分:4)

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

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

通过调用不带参数的函数,类型定义要求函数返回Object类型。我查看了jQuery的文档并且你是对的,返回的对象应该有topleft属性。

不幸的是,由于没有基于返回类型的重载,你将无法在JQuery接口上添加另一个成员。因为,在这种特殊情况下,类型定义根本不是特定的,我建议只修改你的jquery.d.ts文件并更改返回类型,使其看起来如下(可能是字符串而不是数字?):

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

如果您不想修改此文件,您还可以选择在访问其中的任何属性之前将结果转换为any,例如:

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

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

答案 1 :(得分:0)

而不是

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

试试这个

 $('html, body').animate({ scrollTop: $(this).offset().top });
相关问题