如何在TypeScript中扩展JQuery函数

nzk0hqpo  于 5个月前  发布在  jQuery
关注(0)|答案(3)|浏览(66)

我在TypeScript上重写了一些JS代码,遇到了模块导入的问题。例如,我想写我的toggleVisiblity函数。下面是代码:

/// <reference path="../../typings/jquery/jquery.d.ts" />

import * as $ from "jquery";

interface JQuery {
    toggleVisibility(): JQuery;
}

$.fn.extend({
    toggleVisibility: function () {
        return this.each(function () {
            const $this = $(this);
            const visibility = $this.css('visibility') === 'hidden' ? 'visible' : 'hidden';
            $this.css('visibility', visibility);
        });
    }
});

const jQuery = $('foo');
const value = jQuery.val();
jQuery.toggleVisibility();

字符串
但问题是,由于未知原因,toggleVisibility没有添加到JQuery接口,因此我得到一个错误Property 'toggleVisibility' does not exist on type 'JQuery'.,尽管它看到其他方法(valeach等)。
为什么不管用?


的数据

9fkzdhlc

9fkzdhlc1#

试着把

interface JQuery {
    toggleVisibility(): JQuery;
}

字符串
在一个单独的文件中,没有导入/导出语句。这对我来说很有效。虽然知道为什么会很有趣。

编辑:在这个帖子的回答中有一个很好的解释:如何扩展'Window' typescript接口

kfgdxczn

kfgdxczn2#

我找到了解决方案,这对我很有效:
使用JQueryStatic接口进行静态jQuery访问,如$.jGrowl(...)或jQuery.jGrowl(...)或jQuery.toggleVisibility():

interface JQueryStatic {

    ajaxSettings: any;

    jGrowl(object?, f?): JQuery;

}

字符串
对于你自己使用jQuery.fn.extend自定义的函数,使用jQuery接口:

interface JQuery {

    fileinput(object?): void;//custom jquery plugin, had no typings

    enable(): JQuery;

    disable(): JQuery;

    check(): JQuery;

    select_custom(): JQuery;

}


可选,以下是我的扩展jQuery函数:

jQuery.fn.extend({
    disable: function () {
        return this.each(function () {
            this.disabled = true;
        });
    },
    enable: function () {
        return this.each(function () {
            this.disabled = false;
        });
    },
    check: function (checked) {
        if (checked) {
            $(this).parent().addClass('checked');
        } else {
            $(this).parent().removeClass('checked');
        }
        return this.prop('checked', checked);
    },
    select_custom: function (value) {
        $(this).find('.dropdown-menu li').each(function () {
            if ($(this).attr('value') == value) {
                $(this).click();
                return;
            }
        });
    }
});

qq24tv8q

qq24tv8q3#

我也有类似的问题,但我的bootstrapDP函数以同样的方式扩展了JQuery。

解决方案:

declare global {
        interface JQuery {
            bootstrapDP: any;  // replace 'any' with the actual type if known
        }
    }

字符串

说明

这段代码声明了JQuery接口的全局扩展,将我的bootstrapDP方法添加到其中。添加此代码后,TypeScript应该将bootstrapDP识别为jQuery对象上的方法。
以下是一些关于全局增强的文档:link

相关问题