Ale*_*kiy 14 jquery interface typescript es6-modules
我正在重写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();
Run Code Online (Sandbox Code Playgroud)
但问题是,由于未知原因toggleVisibility
没有添加到JQuery
界面,因此我得到一个错误Property 'toggleVisibility' does not exist on type 'JQuery'.
,虽然它看到其他方法(val
,each
等等).
为什么不起作用?
mod*_*777 27
试试吧
interface JQuery {
toggleVisibility(): JQuery;
}
Run Code Online (Sandbox Code Playgroud)
在没有import/export语句的单独文件中.这适合我.虽然知道原因会很有趣.
编辑:在这个帖子的答案中有一个很好的解释这个行为: 如何扩展'Window'打字稿界面
我得到了解决方案,这对我有用:
使用JQueryStatic接口进行静态jQuery访问,例如$ .jGrowl(...)或jQuery.jGrowl(...),或者在您的情况下使用jQuery.toggleVisibility():
interface JQueryStatic {
ajaxSettings: any;
jGrowl(object?, f?): JQuery;
}
Run Code Online (Sandbox Code Playgroud)
对于使用jQuery.fn.extend使用的自定义函数,请使用JQuery接口:
interface JQuery {
fileinput(object?): void;//custom jquery plugin, had no typings
enable(): JQuery;
disable(): JQuery;
check(): JQuery;
select_custom(): JQuery;
}
Run Code Online (Sandbox Code Playgroud)
可选,这是我扩展的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;
}
});
}
});
Run Code Online (Sandbox Code Playgroud)