【问题标题】:How to extend JQuery functions in TypeScript如何在 TypeScript 中扩展 JQuery 函数
【发布时间】:2017-04-18 07:31:47
【问题描述】:

我在 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 等)。

为什么它不起作用?

【问题讨论】:

  • 您的界面JQuery似乎没有与原始界面合并。也许应该进口。你是如何导入 jQuery 的定义的?使用新的 @types 系统?
  • @Paleo 与 tsd install jQuery --save 外遇

标签: jquery typescript interface es6-modules


【解决方案1】:

试着把

interface JQuery {
    toggleVisibility(): JQuery;
}

在没有导入/导出语句的单独文件中。 这对我有用。虽然知道为什么会很有趣。

编辑:在这个帖子的答案中有一个很好的解释: How to extend the 'Window' typescript interface

【讨论】:

  • 我要在 TS github 中创建一个问题,也许它会被修复。谢谢你的回答。
  • @AlexZhukovskiy 请给出问题的链接,我也有兴趣。
  • 对于那些不知道把这个文件放在哪里的人(比如我自己);这个link解释得很好。
  • 哦,谢天谢地,我找到了这篇文章。记录这个 API 让我长出了白发。
【解决方案2】:

我得到了解决方案,这对我有用:

使用 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;
            }
        });
    }
});

【讨论】:

  • 这种方法似乎破坏了常规函数的 JQuery 声明,例如 .click().parent()。知道为什么吗?
猜你喜欢
  • 2019-08-20
  • 2021-05-13
  • 1970-01-01
  • 2011-04-26
  • 1970-01-01
  • 1970-01-01
  • 2016-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多